1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved. 2 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 ==============================================================================*/ 15 16 #ifndef TENSORFLOW_LIB_CORE_BLOCKING_COUNTER_H_ 17 #define TENSORFLOW_LIB_CORE_BLOCKING_COUNTER_H_ 18 19 #include <atomic> 20 21 #include "tensorflow/core/platform/logging.h" 22 #include "tensorflow/core/platform/mutex.h" 23 24 namespace tensorflow { 25 26 class BlockingCounter { 27 public: BlockingCounter(int initial_count)28 BlockingCounter(int initial_count) 29 : state_(initial_count << 1), notified_(false) { 30 CHECK_GE(initial_count, 0); 31 DCHECK_EQ((initial_count << 1) >> 1, initial_count); 32 } 33 ~BlockingCounter()34 ~BlockingCounter() {} 35 DecrementCount()36 inline void DecrementCount() { 37 unsigned int v = state_.fetch_sub(2, std::memory_order_acq_rel) - 2; 38 if (v != 1) { 39 DCHECK_NE(((v + 2) & ~1), 0); 40 return; // either count has not dropped to 0, or waiter is not waiting 41 } 42 mutex_lock l(mu_); 43 DCHECK(!notified_); 44 notified_ = true; 45 cond_var_.notify_all(); 46 } 47 Wait()48 inline void Wait() { 49 unsigned int v = state_.fetch_or(1, std::memory_order_acq_rel); 50 if ((v >> 1) == 0) return; 51 mutex_lock l(mu_); 52 while (!notified_) { 53 cond_var_.wait(l); 54 } 55 } 56 // Wait for the specified time, return false iff the count has not dropped to 57 // zero before the timeout expired. WaitFor(std::chrono::milliseconds ms)58 inline bool WaitFor(std::chrono::milliseconds ms) { 59 unsigned int v = state_.fetch_or(1, std::memory_order_acq_rel); 60 if ((v >> 1) == 0) return true; 61 mutex_lock l(mu_); 62 while (!notified_) { 63 const std::cv_status status = cond_var_.wait_for(l, ms); 64 if (status == std::cv_status::timeout) { 65 return false; 66 } 67 } 68 return true; 69 } 70 71 private: 72 mutex mu_; 73 condition_variable cond_var_; 74 std::atomic<int> state_; // low bit is waiter flag 75 bool notified_; 76 }; 77 78 } // namespace tensorflow 79 80 #endif // TENSORFLOW_LIB_CORE_BLOCKING_COUNTER_H_ 81