Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Diff: main.cpp
- 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