Skip to content

Commit e1baf41

Browse files
committed
Add documentation for the ConditionVariable class
Add a description and example for the ConditionVariable class.
1 parent 52987c3 commit e1baf41

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
## ConditionVariable
2+
3+
The ConditionVariable class provides a mechanism to safely wait for or signal state changes. A common scenario when writing multi threaded code is to protect shared resources with a mutex and then release that mutex to wait for a change of that data. If this is not carefully done this can lead to race condition in the code. A condition variable provides a safe solution to this problem by handling the wait for a state change along with releasing and acquiring the mutex automatically during this waiting period.
4+
5+
### ConditionVariable class reference
6+
7+
Coming soon
8+
9+
### ConditionVariable example
10+
11+
Below is an example of ConditionVariable usage, where one thread is generating events every 1s, and the second thread is waiting for the events and executing some action.
12+
13+
```
14+
#include "mbed.h"
15+
16+
Mutex mutex;
17+
ConditionVariable cond(mutex);
18+
19+
// These variables are protected by locking mutex
20+
uint32_t count = 0;
21+
bool done = false;
22+
23+
void worker_thread()
24+
{
25+
mutex.lock();
26+
do {
27+
printf("Worker: Count %lu\r\n", count);
28+
29+
// Wait for a condition to change
30+
cond.wait();
31+
32+
} while (!done);
33+
printf("Worker: Exiting\r\n");
34+
mutex.unlock();
35+
}
36+
37+
int main() {
38+
Thread thread;
39+
thread.start(worker_thread);
40+
41+
for (int i = 0; i < 5; i++) {
42+
43+
mutex.lock();
44+
// Change count and signal this
45+
count++;
46+
printf("Main: Set count to %lu\r\n", count);
47+
cond.notify_all();
48+
mutex.unlock();
49+
50+
wait(1.0);
51+
}
52+
53+
mutex.lock();
54+
// Change done and signal this
55+
done = true;
56+
printf("Main: Set done\r\n");
57+
cond.notify_all();
58+
mutex.unlock();
59+
60+
thread.join();
61+
}
62+
```

0 commit comments

Comments
 (0)