e03571d15506c1963cb3001d0967a94d73169130
[folly.git] / folly / experimental / EventCount.h
1 /*
2  * Copyright 2012 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef FOLLY_EXPERIMENTAL_EVENTCOUNT_H_
18 #define FOLLY_EXPERIMENTAL_EVENTCOUNT_H_
19
20 #include <syscall.h>
21 #include <linux/futex.h>
22 #include <sys/time.h>
23 #include <climits>
24 #include <atomic>
25 #include <thread>
26
27
28 namespace folly {
29
30 namespace detail {
31
32 int futex(int* uaddr, int op, int val, const struct timespec* timeout,
33           int* uaddr2, int val3) noexcept {
34   return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
35 }
36
37 }  // namespace detail
38
39 /**
40  * Event count: a condition variable for lock free algorithms.
41  *
42  * See http://www.1024cores.net/home/lock-free-algorithms/eventcounts for
43  * details.
44  *
45  * Event counts allow you to convert a non-blocking lock-free / wait-free
46  * algorithm into a blocking one, by isolating the blocking logic.  You call
47  * prepareWait() before checking your condition and then either cancelWait()
48  * or wait() depending on whether the condition was true.  When another
49  * thread makes the condition true, it must call notify() / notifyAll() just
50  * like a regular condition variable.
51  *
52  * If "<" denotes the happens-before relationship, consider 2 threads (T1 and
53  * T2) and 3 events:
54  * - E1: T1 returns from prepareWait
55  * - E2: T1 calls wait
56  *   (obviously E1 < E2, intra-thread)
57  * - E3: T2 calls notifyAll
58  *
59  * If E1 < E3, then E2's wait will complete (and T1 will either wake up,
60  * or not block at all)
61  *
62  * This means that you can use an EventCount in the following manner:
63  *
64  * Waiter:
65  *   if (!condition()) {  // handle fast path first
66  *     for (;;) {
67  *       auto key = eventCount.prepareWait();
68  *       if (condition()) {
69  *         eventCount.cancelWait();
70  *         break;
71  *       } else {
72  *         eventCount.wait(key);
73  *       }
74  *     }
75  *  }
76  *
77  *  (This pattern is encapsulated in await())
78  *
79  * Poster:
80  *   make_condition_true();
81  *   eventCount.notifyAll();
82  *
83  * Note that, just like with regular condition variables, the waiter needs to
84  * be tolerant of spurious wakeups and needs to recheck the condition after
85  * being woken up.  Also, as there is no mutual exclusion implied, "checking"
86  * the condition likely means attempting an operation on an underlying
87  * data structure (push into a lock-free queue, etc) and returning true on
88  * success and false on failure.
89  */
90 class EventCount {
91  public:
92   EventCount() noexcept : epoch_(0), waiters_(0) { }
93
94   class Key {
95     friend class EventCount;
96     explicit Key(int e) noexcept : epoch_(e) { }
97     int epoch_;
98   };
99
100   void notify() noexcept;
101   void notifyAll() noexcept;
102   Key prepareWait() noexcept;
103   void cancelWait() noexcept;
104   void wait(Key key) noexcept;
105
106   /**
107    * Wait for condition() to become true.  Will clean up appropriately if
108    * condition() throws, and then rethrow.
109    */
110   template <class Condition>
111   void await(Condition condition);
112
113  private:
114   void doNotify(int n) noexcept;
115   EventCount(const EventCount&) = delete;
116   EventCount(EventCount&&) = delete;
117   EventCount& operator=(const EventCount&) = delete;
118   EventCount& operator=(EventCount&&) = delete;
119
120   std::atomic<int> epoch_;
121   std::atomic<int> waiters_;
122 };
123
124 inline void EventCount::notify() noexcept {
125   doNotify(1);
126 }
127
128 inline void EventCount::notifyAll() noexcept {
129   doNotify(INT_MAX);
130 }
131
132 inline void EventCount::doNotify(int n) noexcept {
133   // The order is important: epoch_ is incremented before waiters_ is checked.
134   // prepareWait() increments waiters_ before checking epoch_, so it is
135   // impossible to miss a wakeup.
136   ++epoch_;
137   if (waiters_ != 0) {
138     detail::futex(reinterpret_cast<int*>(&epoch_), FUTEX_WAKE, n, nullptr,
139                   nullptr, 0);
140   }
141 }
142
143 inline EventCount::Key EventCount::prepareWait() noexcept {
144   ++waiters_;
145   return Key(epoch_);
146 }
147
148 inline void EventCount::cancelWait() noexcept {
149   --waiters_;
150 }
151
152 inline void EventCount::wait(Key key) noexcept {
153   while (epoch_ == key.epoch_) {
154     detail::futex(reinterpret_cast<int*>(&epoch_), FUTEX_WAIT, key.epoch_,
155                   nullptr, nullptr, 0);
156   }
157   --waiters_;
158 }
159
160 template <class Condition>
161 void EventCount::await(Condition condition) {
162   if (condition()) return;  // fast path
163
164   // condition() is the only thing that may throw, everything else is
165   // noexcept, so we can hoist the try/catch block outside of the loop
166   try {
167     for (;;) {
168       auto key = prepareWait();
169       if (condition()) {
170         cancelWait();
171         break;
172       } else {
173         wait(key);
174       }
175     }
176   } catch (...) {
177     cancelWait();
178     throw;
179   }
180 }
181
182 }  // namespace folly
183
184 #endif /* FOLLY_EXPERIMENTAL_EVENTCOUNT_H_ */
185