Use a shared queue of X items - One thread adds items at random times - The other thread pulls at random times - They need to synchronize when the queue is full (producer) or empty (consumer)!
Diff: main.cpp
- Revision:
- 0:180517623995
- Child:
- 1:58c5e61231be
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Thu Nov 29 17:08:02 2018 +0000 @@ -0,0 +1,75 @@ +#include "mbed.h" + +Queue<int, 10> queue; + +int queue_size = 10; +int end_idx = 0; + +Mutex mutex; +ConditionVariable cond(mutex); +InterruptIn button(USER_BUTTON); + + + bool is_button_pressed = false; + +Thread t1; +Thread t2; +Thread t3; + +void start_producer(){ + int value = 0; + while (true) + { + if (end_idx < queue_size){ + mutex.lock(); + value = end_idx; + queue.put(&value); + printf("PRODUCER: Put value %d \n", end_idx); + end_idx++; + cond.notify_all(); + mutex.unlock(); + } + wait(rand()%10); + } +} + +void start_consumer(){ + while (true) + { + if (end_idx > 0){ + mutex.lock(); + osEvent evt = queue.get(); + if (evt.status == osEventMessage) { + printf("CONSUMER: I got %d\n", *(int *) evt.value.p); + } + end_idx--; + cond.notify_all(); + mutex.unlock(); + } + wait(rand()%5); + } +} + +void toggle (){ + is_button_pressed = true; +} + +void print_status(){ + while (true) { + if(is_button_pressed){ + mutex.lock(); + wait(2); + printf("\n\nThere are %d elements in the queue\n\n", end_idx); + wait(2); + mutex.unlock(); + is_button_pressed = false; + } + } +} + +int main() { + button.rise(&toggle); + t1.start(&start_producer); + t2.start(&start_consumer); + t3.start(&print_status); +}