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

main.cpp

Committer:
cspista
Date:
2022-03-17
Revision:
0:3def6e6a9e93

File content as of revision 0:3def6e6a9e93:

#include "mbed.h"
#include "rtos.h"

Semaphore s(5);                        // a pool of 5 chopsticks
Timer mytime;

void notify(const char* name) {
    printf("%s acquired two chopsticks %8.1f\n\r", name,mytime.read());
}

void test_thread(void const* args) {
    while (true) {
        Thread::wait(1000+rand()%500); //Thinking   
        s.wait();
        s.wait();        
        notify((const char*)args);
        Thread::wait(500+rand()%500);  //Eating
        s.release();
        s.release();        
    }
}

int main (void) {
    mytime.start();
    Thread t2(test_thread, (void *)"Philosopher 2");
    Thread t3(test_thread, (void *)"Philosopher 3");
    Thread t4(test_thread, (void *)"Philosopher 4");
    Thread t5(test_thread, (void *)"Philosopher 5");    
    test_thread((void *)"Philosopher 1");
}