RTOS example - solving the Dining Philosophers problem by using mutexes

Dependencies:   mbed mbed-rtos

main.cpp

Committer:
cspista
Date:
2022-02-24
Revision:
0:bc0e168010f0

File content as of revision 0:bc0e168010f0:

#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);
}