in class exercise

Files at this revision

API Documentation at this revision

Comitter:
iandil
Date:
Fri Nov 16 14:57:57 2018 +0000
Commit message:
producer consumer threadsafed

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 35457e400d4c main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Fri Nov 16 14:57:57 2018 +0000
@@ -0,0 +1,58 @@
+#include "mbed.h"
+typedef struct {
+    int value;
+} message_t;
+const int size = 8;
+MemoryPool<message_t, size> mpool;
+Queue<message_t, size> queue;
+Thread thread1;
+Thread thread2;
+Mutex mutex;
+ConditionVariable cond(mutex);
+int numberOfElement = 0;
+
+void produce() {
+    while(true) {
+        wait(rand()%5);
+        int value = rand();
+        mutex.lock();
+        while(numberOfElement == size) {
+            printf("queue is full");
+            cond.wait();
+        }  
+        message_t *message = mpool.alloc();
+        message->value = value;
+        queue.put(message);
+        numberOfElement++;
+        printf("\nPut Message: %d\n\r"   , message->value);
+        cond.notify_all();
+        mutex.unlock();
+    }
+}
+
+void consume() {
+    while(true) {
+        wait(rand()%5);
+        mutex.lock();
+        while(numberOfElement == 0) {
+            printf("queue is empty");
+            cond.wait();
+        }
+        osEvent evt = queue.get();
+        numberOfElement--;
+        if (evt.status == osEventMessage) {
+            message_t *message = (message_t*)evt.value.p;
+            printf("\nConsumed Message: %d\n\r"   , message->value);
+            mpool.free(message);
+        }
+        cond.notify_all();
+        mutex.unlock();
+        
+    }
+}
+int main() {
+    thread1.start(callback(produce));
+    thread2.start(callback(consume));
+    thread1.join();
+    thread2.join();
+}
\ No newline at end of file
diff -r 000000000000 -r 35457e400d4c mbed-os.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-os.lib	Fri Nov 16 14:57:57 2018 +0000
@@ -0,0 +1,1 @@
+https://github.com/armmbed/mbed-os/#bf6f2c3c6434a6de9eb9511feffa5948b3d1f20f