Mistake on this page?
Report an issue in GitHub or email us
ConditionVariable.h
1 /* Mbed Microcontroller Library
2  * Copyright (c) 2017-2018 ARM Limited
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to deal
6  * in the Software without restriction, including without limitation the rights
7  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8  * copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20  * SOFTWARE.
21  */
22 #ifndef CONDITIONVARIABLE_H
23 #define CONDITIONVARIABLE_H
24 
25 #include <stdint.h>
26 #include "cmsis_os.h"
27 #include "rtos/Mutex.h"
28 #include "rtos/Semaphore.h"
29 
30 #include "platform/NonCopyable.h"
31 
32 namespace rtos {
33 /** \addtogroup rtos */
34 /** @{*/
35 
36 struct Waiter;
37 
38 /** The ConditionVariable class is a synchronization primitive that allows
39  * threads to wait until a particular condition occurs.
40  *
41  * Use the condition variable in conjunction with a mutex to safely wait for
42  * or notify waiters of condition changes to a resource accessible by multiple
43  * threads.
44  *
45  * The thread that intends to wait on a ConditionVariable must:
46  * - Acquire a lock on a mutex.
47  * - Execute `wait`, `wait_for` or `wait_until`. While the thread is waiting,
48  * the mutex is unlocked.
49  * - When the condition variable has been notified, or in the case of `wait_for`
50  * and `wait_until` the timeout expires, the thread is awakened.
51  *
52  * The thread that intends to notify a ConditionVariable must:
53  * - Acquire a lock on the mutex used to construct the condition variable.
54  * - Execute `notify_one` or `notify_all` on the condition variable.
55  *
56  * All threads waiting on the condition variable wake when
57  * `ConditionVariable::notify_all` is called.
58  * At least one thread waiting on the condition variable wakes
59  * when `ConditionVariable::notify_one` is called.
60  *
61  * While a thread is waiting for notification of a
62  * ConditionVariable, it releases the lock held on the mutex.
63  * The ConditionVariable reacquires the mutex lock before exiting the wait
64  * function.
65  *
66  * #### Unspecified behavior
67  * - The thread that is unblocked on `ConditionVariable::notify_one` is
68  * unspecified if there are multiple waiters.
69  * - When `ConditionVariable::notify_one` or `ConditionVariable::notify_all` is
70  * called and there are one or more waiters, and one or more threads
71  * attempting to acquire the condition variable's mutex, the order in which the mutex is
72  * acquired is unspecified.
73  * - Spurious notifications (not triggered by the application) can occur.
74  *
75  * #### Undefined behavior
76  * - Calling wait if the mutex is not locked by the current thread is undefined
77  * behavior.
78  * - The order in which waiting threads acquire the condition variable's
79  * mutex after `ConditionVariable::notify_all` is called is undefined.
80  * - The behavior of `ConditionVariable::wait` and `ConditionVariable::wait_for`
81  * is undefined if the condition variable's mutex is locked more than once by
82  * the calling thread.
83  *
84  * @note Synchronization level: Thread safe
85  *
86  * Example:
87  *
88  * @code
89  * #include "mbed.h"
90  *
91  * Mutex mutex;
92  * ConditionVariable cv(mutex);
93  *
94  * // These variables are protected by locking the mutex.
95  * uint32_t work_count = 0;
96  * bool done = false;
97  *
98  * void worker_thread()
99  * {
100  * // Acquire lock on mutex before accessing protected variables and waiting.
101  * mutex.lock();
102  *
103  * while (done == false) {
104  * printf("Worker thread: Count: %lu\r\n", work_count);
105  *
106  * // Wait for main thread to notify the condition variable.
107  * printf("Worker thread: Waiting\r\n");
108  * cv.wait();
109  * }
110  *
111  * printf("Worker: Exiting\r\n");
112  *
113  * // The condition variable acquires the lock when exiting the `wait` function.
114  * // Unlock mutex when exiting the thread.
115  * mutex.unlock();
116  * }
117  *
118  * int main()
119  * {
120  * Thread thread;
121  * thread.start(worker_thread);
122  *
123  * for (int i = 0; i < 5; i++) {
124  * // Acquire lock on mutex before modifying variables and notifying.
125  * mutex.lock();
126  *
127  * // Change count and notify waiters.
128  * work_count++;
129  * printf("Main thread: Set count to: %lu\r\n", work_count);
130  * printf("Main thread: Notifying worker thread\r\n");
131  * cv.notify_all();
132  *
133  * // Mutex must be unlocked before the worker thread can acquire it.
134  * mutex.unlock();
135  *
136  * wait(1.0);
137  * }
138  *
139  * // Change done and notify waiters of this.
140  * mutex.lock();
141  * done = true;
142  * cv.notify_all();
143  * mutex.unlock();
144  *
145  * thread.join();
146  *
147  * printf("Main: Exiting\r\n");
148  * }
149  * @endcode
150  */
151 
152 class ConditionVariable : private mbed::NonCopyable<ConditionVariable> {
153 public:
154  /** Create and initialize a ConditionVariable object.
155  *
156  * @note You cannot call this function from ISR context.
157  */
158  ConditionVariable(Mutex &mutex);
159 
160  /** Wait for a notification.
161  *
162  * Wait causes the current thread to block until the condition variable
163  * receives a notification from another thread.
164  *
165  * @note - The thread calling this function must be the owner of the
166  * ConditionVariable's mutex, and it must be locked exactly once.
167  *
168  * @note - Spurious notifications can occur, so the caller of this API
169  * should check to make sure the condition the caller is waiting on has
170  * been met.
171  *
172  * @note - The current thread releases the lock while inside the wait
173  * function and reacquires it upon exiting the function.
174  *
175  * Example:
176  * @code
177  * mutex.lock();
178  *
179  * while (!condition_met) {
180  * cond.wait();
181  * }
182  *
183  * function_to_handle_condition();
184  *
185  * mutex.unlock();
186  * @endcode
187  *
188  * @note You cannot call this function from ISR context.
189  */
190  void wait();
191 
192  /** Wait for a notification until the specified time.
193  *
194  * Wait until causes the current thread to block until the condition
195  * variable is notified, or a specific time given by millisec parameter is
196  * reached.
197  *
198  * @param millisec Absolute end time referenced to `Kernel::get_ms_count()`
199  * @return `true` if a timeout occurred, `false` otherwise.
200  *
201  * @note - The thread calling this function must be the owner of the
202  * ConditionVariable's mutex, and it must be locked exactly once.
203  *
204  * @note - Spurious notifications can occur, so the caller of this API
205  * should check to make sure the condition the caller is waiting on has
206  * been met.
207  *
208  * @note - The current thread releases the lock while inside the wait
209  * function and reacquires it upon exiting the function.
210  *
211  * Example:
212  * @code
213  * mutex.lock();
214  * uint64_t end_time = Kernel::get_ms_count() + COND_WAIT_TIMEOUT;
215  *
216  * while (!condition_met) {
217  * if (cond.wait_until(end_time)) {
218  * break;
219  * }
220  * }
221  *
222  * if (condition_met) {
223  * function_to_handle_condition();
224  * }
225  *
226  * mutex.unlock();
227  * @endcode
228  *
229  * @note You cannot call this function from ISR context.
230  */
231  bool wait_until(uint64_t millisec);
232 
233  /** Wait for a notification or timeout.
234  *
235  * `Wait for` causes the current thread to block until the condition
236  * variable receives a notification from another thread, or the timeout
237  * specified by the millisec parameter is reached.
238  *
239  * @param millisec Timeout value or osWaitForever in case of no timeout.
240  * @return `true` if a timeout occurred, `false` otherwise.
241  *
242  * @note - The thread calling this function must be the owner of the
243  * ConditionVariable's mutex, and it must be locked exactly once.
244  *
245  * @note - Spurious notifications can occur, so the caller of this API
246  * should check to make sure the condition the caller is waiting on has
247  * been met.
248  *
249  * @note - The current thread releases the lock while inside the wait
250  * function and reacquire it upon exiting the function.
251  *
252  * Example:
253  * @code
254  * mutex.lock();
255  *
256  * while (!condition_met) {
257  * cond.wait_for(MAX_SLEEP_TIME);
258  * if (!condition_met) {
259  * do_other_work_while_condition_false();
260  * }
261  * }
262  *
263  * if (condition_met) {
264  * function_to_handle_condition();
265  * }
266  *
267  * mutex.unlock();
268  * @endcode
269  *
270  * @note You cannot call this function from ISR context.
271  */
272  bool wait_for(uint32_t millisec);
273 
274  /** Notify one waiter on this condition variable that a condition changed.
275  *
276  * This function unblocks one of the threads waiting for the condition
277  * variable.
278  *
279  * @note - The thread calling this function must be the owner of the
280  * ConditionVariable's mutex.
281  *
282  * @note - The thread that is unblocked on ConditionVariable::notify_one is
283  * undefined if there are multiple waiters.
284  *
285  * @note You cannot call this function from ISR context.
286  */
287  void notify_one();
288 
289  /** Notify all waiters on this condition variable that a condition changed.
290  *
291  * This function unblocks all of the threads waiting for the condition
292  * variable.
293  *
294  * @note - The thread calling this function must be the owner of the
295  * ConditionVariable's mutex.
296  *
297  * @note - If there are one or more waiters and one or more threads
298  * attempting to acquire the condition variable's mutex the order in which
299  * the mutex is acquired is undefined.
300  *
301  * @note You cannot call this function from ISR context.
302  */
303  void notify_all();
304 
305  /** ConditionVariable destructor.
306  *
307  * @note You cannot call this function from ISR context.
308  */
310 
311 #if !defined(DOXYGEN_ONLY)
312 protected:
313  struct Waiter {
314  Waiter();
315  Semaphore sem;
316  Waiter *prev;
317  Waiter *next;
318  bool in_list;
319  };
320 
321  static void _add_wait_list(Waiter **wait_list, Waiter *waiter);
322  static void _remove_wait_list(Waiter **wait_list, Waiter *waiter);
323  Mutex &_mutex;
324  Waiter *_wait_list;
325 #endif // !defined(DOXYGEN_ONLY)
326 };
327 
328 }
329 #endif
330 
331 /** @}*/
void notify_all()
Notify all waiters on this condition variable that a condition changed.
The Semaphore class is used to manage and protect access to a set of shared resources.
Definition: Semaphore.h:46
ConditionVariable(Mutex &mutex)
Create and initialize a ConditionVariable object.
~ConditionVariable()
ConditionVariable destructor.
bool wait_for(uint32_t millisec)
Wait for a notification or timeout.
Prevents generation of copy constructor and copy assignment operator in derived classes.
Definition: NonCopyable.h:168
void wait()
Wait for a notification.
bool wait_until(uint64_t millisec)
Wait for a notification until the specified time.
void notify_one()
Notify one waiter on this condition variable that a condition changed.
The Mutex class is used to synchronize the execution of threads.
Definition: Mutex.h:66
The ConditionVariable class is a synchronization primitive that allows threads to wait until a partic...
Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.