Modified version oft the Dining Philosopher Problem - here any chopstick can be used, so the five chopstick are represented báy a counting semaphore initialized with a value of 5.

Dependencies:   mbed mbed-rtos

Committer:
cspista
Date:
Thu Mar 17 12:34:27 2022 +0000
Revision:
0:3def6e6a9e93
Final version

Who changed what in which revision?

UserRevisionLine numberNew contents of line
cspista 0:3def6e6a9e93 1 #include "mbed.h"
cspista 0:3def6e6a9e93 2 #include "rtos.h"
cspista 0:3def6e6a9e93 3
cspista 0:3def6e6a9e93 4 Semaphore s(5); // a pool of 5 chopsticks
cspista 0:3def6e6a9e93 5 Timer mytime;
cspista 0:3def6e6a9e93 6
cspista 0:3def6e6a9e93 7 void notify(const char* name) {
cspista 0:3def6e6a9e93 8 printf("%s acquired two chopsticks %8.1f\n\r", name,mytime.read());
cspista 0:3def6e6a9e93 9 }
cspista 0:3def6e6a9e93 10
cspista 0:3def6e6a9e93 11 void test_thread(void const* args) {
cspista 0:3def6e6a9e93 12 while (true) {
cspista 0:3def6e6a9e93 13 Thread::wait(1000+rand()%500); //Thinking
cspista 0:3def6e6a9e93 14 s.wait();
cspista 0:3def6e6a9e93 15 s.wait();
cspista 0:3def6e6a9e93 16 notify((const char*)args);
cspista 0:3def6e6a9e93 17 Thread::wait(500+rand()%500); //Eating
cspista 0:3def6e6a9e93 18 s.release();
cspista 0:3def6e6a9e93 19 s.release();
cspista 0:3def6e6a9e93 20 }
cspista 0:3def6e6a9e93 21 }
cspista 0:3def6e6a9e93 22
cspista 0:3def6e6a9e93 23 int main (void) {
cspista 0:3def6e6a9e93 24 mytime.start();
cspista 0:3def6e6a9e93 25 Thread t2(test_thread, (void *)"Philosopher 2");
cspista 0:3def6e6a9e93 26 Thread t3(test_thread, (void *)"Philosopher 3");
cspista 0:3def6e6a9e93 27 Thread t4(test_thread, (void *)"Philosopher 4");
cspista 0:3def6e6a9e93 28 Thread t5(test_thread, (void *)"Philosopher 5");
cspista 0:3def6e6a9e93 29 test_thread((void *)"Philosopher 1");
cspista 0:3def6e6a9e93 30 }