István Cserny / Mbed 2 deprecated Lab07_RTOS_philosophers

Dependencies:   mbed mbed-rtos

Revision:
0:bc0e168010f0
diff -r 000000000000 -r bc0e168010f0 main.cpp
--- /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