luozenglin commented on code in PR #19256:
URL: https://github.com/apache/doris/pull/19256#discussion_r1185950624


##########
be/src/runtime/memory/mem_tracker.h:
##########
@@ -64,32 +64,39 @@ class MemTracker {
         MemCounter() : _current_value(0), _peak_value(0) {}
 
         void add(int64_t delta) {
-            _current_value.fetch_add(delta, std::memory_order_relaxed);
-            update_peak();
+            auto value = _current_value.fetch_add(delta, 
std::memory_order_relaxed) + delta;
+            update_peak(value);
         }
 
         void add_no_update_peak(int64_t delta) {
             _current_value.fetch_add(delta, std::memory_order_relaxed);
         }
 
         bool try_add(int64_t delta, int64_t max) {
-            if (UNLIKELY(_current_value.load(std::memory_order_relaxed) + 
delta > max))
-                return false;
-            _current_value.fetch_add(delta, std::memory_order_relaxed);
-            update_peak();
+            auto cur_val = _current_value.load(std::memory_order_relaxed);
+            auto new_val = 0;
+            do {
+                new_val = cur_val + delta;
+                if (UNLIKELY(new_val > max)) {
+                    return false;
+                }
+            } while (UNLIKELY(!_current_value.compare_exchange_weak(cur_val, 
new_val,
+                                                                    
std::memory_order_relaxed)));
+            update_peak(new_val);
             return true;
         }
 
+        void sub(int64_t delta) { _current_value.fetch_sub(delta, 
std::memory_order_relaxed); }
+
         void set(int64_t v) {
             _current_value.store(v, std::memory_order_relaxed);
-            update_peak();
+            update_peak(v);
         }
 
-        void update_peak() {
-            if (_current_value.load(std::memory_order_relaxed) >
-                _peak_value.load(std::memory_order_relaxed)) {
-                
_peak_value.store(_current_value.load(std::memory_order_relaxed),
-                                  std::memory_order_relaxed);
+        void update_peak(int64_t value) {
+            auto pre_value = _peak_value.load(std::memory_order_relaxed);

Review Comment:
   compare_exchange_weak updates pre_value if the comparison fails, so next 
enters the loop the pre_value will be 10



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org
For additional commands, e-mail: commits-h...@doris.apache.org

Reply via email to