producer consumer for exercise 2

Files at this revision

API Documentation at this revision

Comitter:
mcalzana
Date:
Wed Nov 28 16:46:47 2018 +0000
Commit message:
exercise 2

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
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Wed Nov 28 16:46:47 2018 +0000
@@ -0,0 +1,53 @@
+#include "mbed.h"
+Mutex mutex;
+ConditionVariable cond(mutex); 
+const int size = 3;
+int numberOfItems = 0;
+
+typedef struct{
+    int number;
+}message_t;
+MemoryPool<message_t, size> mpool;
+Queue<message_t, size> queue;
+
+void consumer(){
+     while(true){
+        wait(rand() % 3);
+        mutex.lock();
+        if(numberOfItems > 0){
+            osEvent evt = queue.get();
+            message_t *message = (message_t*)evt.value.p;
+            printf("number %d consumed", message->number);
+            numberOfItems--;
+            printf("Consumer. there are %d elements in queue\n", numberOfItems);
+            mpool.free(message);
+        }else{
+            printf("Consumer. queue is empty\n");
+        }
+        cond.notify_all();
+        mutex.unlock();
+    }
+}
+
+
+int main() {
+    Thread thread;
+    thread.start(consumer);
+
+    //Producer
+    while(true){
+        wait(rand() % 3);
+        mutex.lock();
+        if(numberOfItems < size){
+            message_t *message = mpool.alloc();
+            message->number = rand();
+            queue.put(message);
+            numberOfItems++;
+            printf("Producer. there are %d elements in queue\n", numberOfItems);
+        }else{
+            printf("Producer. queue full\n");
+        }
+        cond.notify_all();
+        mutex.unlock();
+    }   
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-os.lib	Wed Nov 28 16:46:47 2018 +0000
@@ -0,0 +1,1 @@
+https://github.com/armmbed/mbed-os/#bf6f2c3c6434a6de9eb9511feffa5948b3d1f20f