Producer-Consumer

Files at this revision

API Documentation at this revision

Comitter:
redona
Date:
Fri Nov 30 11:43:13 2018 +0000
Commit message:
Producer-Consumer

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed-os.lib Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r c9ab786082e4 main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Fri Nov 30 11:43:13 2018 +0000
@@ -0,0 +1,61 @@
+#include "mbed.h"
+
+typedef struct {
+  int value;
+} message_t;
+Mutex mutex;
+const int queue_size = 10;
+ConditionVariable cond(mutex);
+MemoryPool<message_t, queue_size> mpool;
+Queue<message_t, queue_size> queue;
+Thread thread_producer;
+Thread thread_consumer;
+
+int pointer = 0;
+
+void producer () {
+    while (true) {
+        wait(rand()%3);
+        mutex.lock(); 
+        int rand_value = rand(); 
+        message_t *message = mpool.alloc();
+        message->value = rand_value;
+        queue.put(message);
+        pointer++;
+        printf("\nProducer value %d \n", message->value);
+        while (pointer == queue_size){
+            printf("\nThe queue is full, wait a consumer\n");
+            cond.wait();
+            }
+        cond.notify_all();
+        mutex.unlock();
+    }
+}
+
+void consumer(){
+     while (true) {
+        wait(rand()%5);
+        mutex.lock();
+          while (pointer == 0){
+           printf("\nThe queue is empty, wait for a producer.\n");
+           cond.wait();
+            }
+        osEvent evt = queue.get();
+        pointer--;
+        if (evt.status == osEventMessage) {
+            message_t *message = (message_t*)evt.value.p;
+            printf("\nGot value %.d .\n"   , message->value);
+            mpool.free(message);
+        }
+        cond.notify_all();
+        mutex.unlock();
+    }
+
+ }
+
+int main () {
+    
+    thread_producer.start(&producer);
+    thread_consumer.start(&consumer);
+
+}
diff -r 000000000000 -r c9ab786082e4 mbed-os.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-os.lib	Fri Nov 30 11:43:13 2018 +0000
@@ -0,0 +1,1 @@
+https://github.com/armmbed/mbed-os/#bf6f2c3c6434a6de9eb9511feffa5948b3d1f20f