Example use of the ConditionVariable class.

Committer:
c1728p9
Date:
Thu Jan 04 01:09:36 2018 +0000
Revision:
0:36d0e9449606
Initial Commit

Who changed what in which revision?

UserRevisionLine numberNew contents of line
c1728p9 0:36d0e9449606 1 #include "mbed.h"
c1728p9 0:36d0e9449606 2
c1728p9 0:36d0e9449606 3 Mutex mutex;
c1728p9 0:36d0e9449606 4 ConditionVariable cond(mutex);
c1728p9 0:36d0e9449606 5
c1728p9 0:36d0e9449606 6 // These variables are protected by locking mutex
c1728p9 0:36d0e9449606 7 uint32_t count = 0;
c1728p9 0:36d0e9449606 8 bool done = false;
c1728p9 0:36d0e9449606 9
c1728p9 0:36d0e9449606 10 void worker_thread()
c1728p9 0:36d0e9449606 11 {
c1728p9 0:36d0e9449606 12 mutex.lock();
c1728p9 0:36d0e9449606 13 do {
c1728p9 0:36d0e9449606 14 printf("Worker: Count %lu\r\n", count);
c1728p9 0:36d0e9449606 15
c1728p9 0:36d0e9449606 16 // Wait for a condition to change
c1728p9 0:36d0e9449606 17 cond.wait();
c1728p9 0:36d0e9449606 18
c1728p9 0:36d0e9449606 19 } while (!done);
c1728p9 0:36d0e9449606 20 printf("Worker: Exiting\r\n");
c1728p9 0:36d0e9449606 21 mutex.unlock();
c1728p9 0:36d0e9449606 22 }
c1728p9 0:36d0e9449606 23
c1728p9 0:36d0e9449606 24 int main() {
c1728p9 0:36d0e9449606 25 Thread thread;
c1728p9 0:36d0e9449606 26 thread.start(worker_thread);
c1728p9 0:36d0e9449606 27
c1728p9 0:36d0e9449606 28 for (int i = 0; i < 5; i++) {
c1728p9 0:36d0e9449606 29
c1728p9 0:36d0e9449606 30 mutex.lock();
c1728p9 0:36d0e9449606 31 // Change count and signal this
c1728p9 0:36d0e9449606 32 count++;
c1728p9 0:36d0e9449606 33 printf("Main: Set count to %lu\r\n", count);
c1728p9 0:36d0e9449606 34 cond.notify_all();
c1728p9 0:36d0e9449606 35 mutex.unlock();
c1728p9 0:36d0e9449606 36
c1728p9 0:36d0e9449606 37 wait(1.0);
c1728p9 0:36d0e9449606 38 }
c1728p9 0:36d0e9449606 39
c1728p9 0:36d0e9449606 40 mutex.lock();
c1728p9 0:36d0e9449606 41 // Change done and signal this
c1728p9 0:36d0e9449606 42 done = true;
c1728p9 0:36d0e9449606 43 printf("Main: Set done\r\n");
c1728p9 0:36d0e9449606 44 cond.notify_all();
c1728p9 0:36d0e9449606 45 mutex.unlock();
c1728p9 0:36d0e9449606 46
c1728p9 0:36d0e9449606 47 thread.join();
c1728p9 0:36d0e9449606 48 }