1// Copyright 2017 The Abseil Authors.
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// https://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// barrier.h
17// -----------------------------------------------------------------------------
18
19#ifndef ABSL_SYNCHRONIZATION_BARRIER_H_
20#define ABSL_SYNCHRONIZATION_BARRIER_H_
21
22#include "absl/base/thread_annotations.h"
23#include "absl/synchronization/mutex.h"
24
25namespace absl {
26
27// Barrier
28//
29// This class creates a barrier which blocks threads until a prespecified
30// threshold of threads (`num_threads`) utilizes the barrier. A thread utilizes
31// the `Barrier` by calling `Block()` on the barrier, which will block that
32// thread; no call to `Block()` will return until `num_threads` threads have
33// called it.
34//
35// Exactly one call to `Block()` will return `true`, which is then responsible
36// for destroying the barrier; because stack allocation will cause the barrier
37// to be deleted when it is out of scope, barriers should not be stack
38// allocated.
39//
40// Example:
41//
42// // Main thread creates a `Barrier`:
43// barrier = new Barrier(num_threads);
44//
45// // Each participating thread could then call:
46// if (barrier->Block()) delete barrier; // Exactly one call to `Block()`
47// // returns `true`; that call
48// // deletes the barrier.
49class Barrier {
50 public:
51 // `num_threads` is the number of threads that will participate in the barrier
52 explicit Barrier(int num_threads)
53 : num_to_block_(num_threads), num_to_exit_(num_threads) {}
54
55 Barrier(const Barrier&) = delete;
56 Barrier& operator=(const Barrier&) = delete;
57
58 // Barrier::Block()
59 //
60 // Blocks the current thread, and returns only when the `num_threads`
61 // threshold of threads utilizing this barrier has been reached. `Block()`
62 // returns `true` for precisely one caller, which may then destroy the
63 // barrier.
64 //
65 // Memory ordering: For any threads X and Y, any action taken by X
66 // before X calls `Block()` will be visible to Y after Y returns from
67 // `Block()`.
68 bool Block();
69
70 private:
71 Mutex lock_;
72 int num_to_block_ GUARDED_BY(lock_);
73 int num_to_exit_ GUARDED_BY(lock_);
74};
75
76} // namespace absl
77#endif // ABSL_SYNCHRONIZATION_BARRIER_H_
78