ProducerConsumer assignment

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
framtk
Date:
Thu Nov 29 19:44:25 2018 +0000
Commit message:
done

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
mbed.bld Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r 893cec0c5c61 main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Thu Nov 29 19:44:25 2018 +0000
@@ -0,0 +1,76 @@
+#include "mbed.h"
+#define MAX_ELEMENTS 5
+
+Mutex mutex1;
+Mutex mutex2;
+ConditionVariable full(mutex1);
+ConditionVariable empty(mutex2);
+Thread producer;
+Thread consumer;
+
+
+typedef struct element_s{
+    uint8_t counter;
+} element_t;
+
+
+MemoryPool<element_t, MAX_ELEMENTS> mpool;
+Queue<element_t, MAX_ELEMENTS> queue;
+volatile int current_elements = 0;
+
+
+
+void producer_thread(void) {
+    while (1) {
+      mutex1.lock();
+      if (current_elements == MAX_ELEMENTS) {
+        printf("The queue is full!\n");
+        full.wait();    
+      }
+      element_t *element = mpool.alloc();
+      element->counter = current_elements+1; 
+      queue.put(element);
+      current_elements++;
+      printf("Adding element, now the queue is %d\n", current_elements);
+      if (current_elements == 1) {
+        full.notify_all();
+      }
+      mutex1.unlock();
+      // randomly decide to keep producing or start consuming
+      if (rand() % 10 < 2) {
+            wait(rand()%2);
+    }
+    }
+}
+
+void consumer_thread(void) {
+    while (1) {
+        mutex1.lock();
+        if (current_elements == 0) {
+          printf("The queue is empty!\n");
+          full.wait();    
+        }
+        osEvent evt = queue.get();
+        if (evt.status == osEventMessage) {
+          element_t *element = (element_t*)evt.value.p;
+          mpool.free(element);
+          current_elements--;
+        }
+        
+        printf("Removing element, now the queue is %d\n", current_elements);
+        if (current_elements == MAX_ELEMENTS-1) {
+          full.notify_all();   
+        }    
+        mutex1.unlock();
+        
+        // randomly decide to keep consuming or start producing
+        if (rand() % 10 < 2) {
+            wait(rand()%2);
+        }
+    }
+}
+
+int main() {
+    producer.start(producer_thread);
+    consumer.start(consumer_thread);
+}
diff -r 000000000000 -r 893cec0c5c61 mbed-os.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-os.lib	Thu Nov 29 19:44:25 2018 +0000
@@ -0,0 +1,1 @@
+https://github.com/armmbed/mbed-os/#bf6f2c3c6434a6de9eb9511feffa5948b3d1f20f
diff -r 000000000000 -r 893cec0c5c61 mbed.bld
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Thu Nov 29 19:44:25 2018 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/22da6e220af6
\ No newline at end of file