Example use of the ConditionVariable class.

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 
00003 Mutex mutex;
00004 ConditionVariable cond(mutex);
00005 
00006 // These variables are protected by locking mutex
00007 uint32_t count = 0;
00008 bool done = false;
00009 
00010 void worker_thread()
00011 {
00012     mutex.lock();
00013     do {
00014         printf("Worker: Count %lu\r\n", count);
00015 
00016         // Wait for a condition to change
00017         cond.wait();
00018 
00019     } while (!done);
00020     printf("Worker: Exiting\r\n");
00021     mutex.unlock();
00022 }
00023 
00024 int main() {
00025     Thread thread;
00026     thread.start(worker_thread);
00027 
00028     for (int i = 0; i < 5; i++) {
00029 
00030         mutex.lock();
00031         // Change count and signal this
00032         count++;
00033         printf("Main: Set count to %lu\r\n", count);
00034         cond.notify_all();
00035         mutex.unlock();
00036 
00037         wait(1.0);
00038     }
00039 
00040     mutex.lock();
00041     // Change done and signal this
00042     done = true;
00043     printf("Main: Set done\r\n");
00044     cond.notify_all();
00045     mutex.unlock();
00046 
00047     thread.join();
00048 }