Barrier.h
Go to the documentation of this file.
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@google.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 
10 // Barrier is an object that allows one or more threads to wait until
11 // Notify has been called a specified number of times.
12 
13 #ifndef EIGEN_CXX11_THREADPOOL_BARRIER_H
14 #define EIGEN_CXX11_THREADPOOL_BARRIER_H
15 
16 #include "./InternalHeaderCheck.h"
17 
18 namespace Eigen {
19 
20 class Barrier {
21  public:
22  Barrier(unsigned int count) : state_(count << 1), notified_(false) {
23  eigen_plain_assert(((count << 1) >> 1) == count);
24  }
25  ~Barrier() { eigen_plain_assert((state_ >> 1) == 0); }
26 
27  void Notify() {
28  unsigned int v = state_.fetch_sub(2, std::memory_order_acq_rel) - 2;
29  if (v != 1) {
30  // Clear the lowest bit (waiter flag) and check that the original state
31  // value was not zero. If it was zero, it means that notify was called
32  // more times than the original count.
33  eigen_plain_assert(((v + 2) & ~1) != 0);
34  return; // either count has not dropped to 0, or waiter is not waiting
35  }
38  notified_ = true;
39  cv_.notify_all();
40  }
41 
42  void Wait() {
43  unsigned int v = state_.fetch_or(1, std::memory_order_acq_rel);
44  if ((v >> 1) == 0) return;
46  while (!notified_) {
47  cv_.wait(l);
48  }
49  }
50 
51  private:
54  std::atomic<unsigned int> state_; // low bit is waiter flag
55  bool notified_;
56 };
57 
58 // Notification is an object that allows a user to to wait for another
59 // thread to signal a notification that an event has occurred.
60 //
61 // Multiple threads can wait on the same Notification object,
62 // but only one caller must call Notify() on the object.
65 };
66 
67 } // namespace Eigen
68 
69 #endif // EIGEN_CXX11_THREADPOOL_BARRIER_H
Array< int, Dynamic, 1 > v
#define eigen_plain_assert(condition)
Definition: Assert.h:156
#define EIGEN_MUTEX
Definition: ThreadPool:55
#define EIGEN_MUTEX_LOCK
Definition: ThreadPool:58
#define EIGEN_CONDVAR
Definition: ThreadPool:61
bool notified_
Definition: Barrier.h:55
EIGEN_CONDVAR cv_
Definition: Barrier.h:53
void Wait()
Definition: Barrier.h:42
EIGEN_MUTEX mu_
Definition: Barrier.h:52
std::atomic< unsigned int > state_
Definition: Barrier.h:54
void Notify()
Definition: Barrier.h:27
Barrier(unsigned int count)
Definition: Barrier.h:22
: InteropHeaders
Definition: Core:139