1/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations 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
24namespace tensorflow {
25
26class InternalIncrementalBarrier {
27 public:
28 explicit InternalIncrementalBarrier(IncrementalBarrier::DoneCallback callback)
29 : left_(1), done_callback_(std::move(callback)) {}
30
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
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
54IncrementalBarrier::IncrementalBarrier(DoneCallback done_callback)
55 : internal_barrier_(
56 new InternalIncrementalBarrier(std::move(done_callback))) {}
57
58IncrementalBarrier::~IncrementalBarrier() { (*internal_barrier_)(); }
59
60IncrementalBarrier::BarrierCallback IncrementalBarrier::Inc() {
61 return internal_barrier_->Inc();
62}
63
64} // namespace tensorflow
65