Eigen  5.0.1
 
Loading...
Searching...
No Matches
Barrier.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2018 Rasmus Munk Larsen <rmlarsen@gmail.com>
5//
6// This Source Code Form is subject to the terms of the Mozilla
7// Public License v. 2.0. If a copy of the MPL was not distributed
8// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9// SPDX-License-Identifier: MPL-2.0
10
11// Barrier is an object that allows one or more threads to wait until
12// Notify has been called a specified number of times.
13
14#ifndef EIGEN_THREADPOOL_BARRIER_H
15#define EIGEN_THREADPOOL_BARRIER_H
16
17// IWYU pragma: private
18#include "./InternalHeaderCheck.h"
19
20namespace Eigen {
21
22class Barrier {
23 public:
24 Barrier(unsigned int count) : state_(count << 1), notified_(false) {
25 eigen_plain_assert(((count << 1) >> 1) == count);
26 }
27 ~Barrier() { eigen_plain_assert((state_ >> 1) == 0); }
28
29 void Notify() {
30 unsigned int v = state_.fetch_sub(2, std::memory_order_acq_rel) - 2;
31 if (v != 1) {
32 // Clear the lowest bit (waiter flag) and check that the original state
33 // value was not zero. If it was zero, it means that notify was called
34 // more times than the original count.
35 eigen_plain_assert(((v + 2) & ~1) != 0);
36 return; // either count has not dropped to 0, or waiter is not waiting
37 }
38 EIGEN_MUTEX_LOCK l(mu_);
39 eigen_plain_assert(!notified_);
40 notified_ = true;
41 cv_.notify_all();
42 }
43
44 void Wait() {
45 unsigned int v = state_.fetch_or(1, std::memory_order_acq_rel);
46 if ((v >> 1) == 0) return;
47 EIGEN_MUTEX_LOCK l(mu_);
48 while (!notified_) {
49 cv_.wait(l);
50 }
51 }
52
53 private:
54 EIGEN_MUTEX mu_;
55 EIGEN_CONDVAR cv_;
56 std::atomic<unsigned int> state_; // low bit is waiter flag
57 bool notified_;
58};
59
60// Notification is an object that allows a user to wait for another
61// thread to signal a notification that an event has occurred.
62//
63// Multiple threads can wait on the same Notification object,
64// but only one caller must call Notify() on the object.
65struct Notification : Barrier {
66 Notification() : Barrier(1) {}
67};
68
69} // namespace Eigen
70
71#endif // EIGEN_THREADPOOL_BARRIER_H