1 /* Copyright 2020 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 #include "tensorflow/core/util/incremental_barrier.h" 17 18 #include <atomic> 19 #include <functional> 20 21 #include "absl/functional/bind_front.h" 22 #include "tensorflow/core/platform/logging.h" 23 24 namespace tensorflow { 25 26 class InternalIncrementalBarrier { 27 public: InternalIncrementalBarrier(IncrementalBarrier::DoneCallback callback)28 explicit InternalIncrementalBarrier(IncrementalBarrier::DoneCallback callback) 29 : left_(1), done_callback_(std::move(callback)) {} 30 operator ()()31 void operator()() { 32 DCHECK_GE(left_.load(std::memory_order_relaxed), 0); 33 34 if (left_.fetch_sub(1, std::memory_order_acq_rel) - 1 == 0) { 35 IncrementalBarrier::DoneCallback done_callback = 36 std::move(done_callback_); 37 delete this; 38 done_callback(); 39 } 40 } 41 Inc()42 IncrementalBarrier::BarrierCallback Inc() { 43 left_.fetch_add(1, std::memory_order_acq_rel); 44 45 // std::bind_front is only available ever since C++20. 46 return absl::bind_front(&InternalIncrementalBarrier::operator(), this); 47 } 48 49 private: 50 std::atomic<int> left_; 51 IncrementalBarrier::DoneCallback done_callback_; 52 }; 53 IncrementalBarrier(DoneCallback done_callback)54IncrementalBarrier::IncrementalBarrier(DoneCallback done_callback) 55 : internal_barrier_( 56 new InternalIncrementalBarrier(std::move(done_callback))) {} 57 ~IncrementalBarrier()58IncrementalBarrier::~IncrementalBarrier() { (*internal_barrier_)(); } 59 Inc()60IncrementalBarrier::BarrierCallback IncrementalBarrier::Inc() { 61 return internal_barrier_->Inc(); 62 } 63 64 } // namespace tensorflow 65