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