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)!
Revision 1:58c5e61231be, committed 2018-11-29
- Comitter:
- vicara
- Date:
- Thu Nov 29 17:57:31 2018 +0000
- Parent:
- 0:180517623995
- Commit message:
- frunzia
Changed in this revision
| main.cpp | Show annotated file Show diff for this revision Revisions of this file |
--- a/main.cpp Thu Nov 29 17:08:02 2018 +0000
+++ b/main.cpp Thu Nov 29 17:57:31 2018 +0000
@@ -1,52 +1,61 @@
#include "mbed.h"
-Queue<int, 10> queue;
-
-int queue_size = 10;
-int end_idx = 0;
+typedef struct {
+ int value;
+} message_t;
+const int queue_size = 10;
+MemoryPool<message_t, queue_size> mpool;
+Queue<message_t, queue_size> queue;
+int elements_num = 0;
Mutex mutex;
ConditionVariable cond(mutex);
InterruptIn button(USER_BUTTON);
-
-
- bool is_button_pressed = false;
+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()%3);
+ mutex.lock();
+ int value = rand();
+ while(elements_num == queue_size) {
+ printf("The queue is full, cannot put.\n");
+ cond.wait();
}
- wait(rand()%10);
+ message_t *message = mpool.alloc();
+ message->value = value;
+ queue.put(message);
+ elements_num++;
+ printf("PRODUCER: Put value %d \n", message->value);
+ cond.notify_all();
+ mutex.unlock();
}
}
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);
+ wait(rand()%10);
+ mutex.lock();
+ while(elements_num == 0) {
+ printf("The queue is empty. Nothing to consume.\n");
+ cond.wait();
+ }
+ osEvent evt = queue.get();
+ elements_num--;
+ if (evt.status == osEventMessage) {
+ message_t *message = (message_t*)evt.value.p;
+ printf("CONSUMER: I got %d\n", message->value);
+ mpool.free(message);
+ }
+ cond.notify_all();
+ mutex.unlock();
}
}
@@ -59,7 +68,7 @@
if(is_button_pressed){
mutex.lock();
wait(2);
- printf("\n\nThere are %d elements in the queue\n\n", end_idx);
+ printf("\n\nThere are %d elements in the queue\n\n", elements_num);
wait(2);
mutex.unlock();
is_button_pressed = false;