RTOS example - solving the Dining Philosophers problem by using mutexes

Dependencies:   mbed mbed-rtos

Files at this revision

API Documentation at this revision

Comitter:
cspista
Date:
Thu Feb 24 08:09:20 2022 +0000
Commit message:
final version

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed-rtos.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
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Thu Feb 24 08:09:20 2022 +0000
@@ -0,0 +1,48 @@
+#include "mbed.h"
+#include "rtos.h"
+// Mutex stdio_mutex;
+Mutex chopstick[5];  //Array of mutexes representing the 5 chopsticks
+Serial pc(USBTX,USBRX);     //UART via ST-Link
+
+void notify(int num, int state)
+{
+    // stdio_mutex.lock();
+    if(state) {
+        pc.printf("Philospher %d is EATING \n\r", num);
+    } else {
+        pc.printf("Philospher %d is thinking \n\r", num);
+    }
+    // stdio_mutex.unlock();
+}
+
+void philosopher(void const *args)
+{
+    while (true) {
+        if(chopstick[(int)args-1].trylock()) {
+            if(chopstick[(int)args%5].trylock()) {
+                notify((int)args,1);                //Start EATING
+                Thread::wait(1000+rand()%1000);
+                chopstick[(int)args%5].unlock();    //Release chopsticks
+                chopstick[(int)args-1].unlock();
+                notify((int)args,0);                //Start Thinking
+                Thread::wait(2000+rand()%2000);     //Get's hungry after this time...
+            } else {
+                chopstick[(int)args-1].unlock();
+                Thread::wait(100+rand()%100);       //Wait for random time if failed
+            }
+        } else {
+            Thread::wait(100+rand()%100);           //Wait for random time if failed
+        }
+
+    }
+}
+
+int main()
+{
+    pc.baud(115200);
+    Thread t2(philosopher, (void *)2U);
+    Thread t3(philosopher, (void *)3U);
+    Thread t4(philosopher, (void *)4U);
+    Thread t5(philosopher, (void *)5U);
+    philosopher((void *)1U);
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-rtos.lib	Thu Feb 24 08:09:20 2022 +0000
@@ -0,0 +1,1 @@
+https://os.mbed.com/users/mbed_official/code/mbed-rtos/#5713cbbdb706
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Thu Feb 24 08:09:20 2022 +0000
@@ -0,0 +1,1 @@
+https://os.mbed.com/users/mbed_official/code/mbed/builds/65be27845400
\ No newline at end of file