István Cserny / Mbed 2 deprecated Lab07_RTOS_philosophers

Dependencies:   mbed mbed-rtos

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "rtos.h"
00003 // Mutex stdio_mutex;
00004 Mutex chopstick[5];  //Array of mutexes representing the 5 chopsticks
00005 Serial pc(USBTX,USBRX);     //UART via ST-Link
00006 
00007 void notify(int num, int state)
00008 {
00009     // stdio_mutex.lock();
00010     if(state) {
00011         pc.printf("Philospher %d is EATING \n\r", num);
00012     } else {
00013         pc.printf("Philospher %d is thinking \n\r", num);
00014     }
00015     // stdio_mutex.unlock();
00016 }
00017 
00018 void philosopher(void const *args)
00019 {
00020     while (true) {
00021         if(chopstick[(int)args-1].trylock()) {
00022             if(chopstick[(int)args%5].trylock()) {
00023                 notify((int)args,1);                //Start EATING
00024                 Thread::wait(1000+rand()%1000);
00025                 chopstick[(int)args%5].unlock();    //Release chopsticks
00026                 chopstick[(int)args-1].unlock();
00027                 notify((int)args,0);                //Start Thinking
00028                 Thread::wait(2000+rand()%2000);     //Get's hungry after this time...
00029             } else {
00030                 chopstick[(int)args-1].unlock();
00031                 Thread::wait(100+rand()%100);       //Wait for random time if failed
00032             }
00033         } else {
00034             Thread::wait(100+rand()%100);           //Wait for random time if failed
00035         }
00036 
00037     }
00038 }
00039 
00040 int main()
00041 {
00042     pc.baud(115200);
00043     Thread t2(philosopher, (void *)2U);
00044     Thread t3(philosopher, (void *)3U);
00045     Thread t4(philosopher, (void *)4U);
00046     Thread t5(philosopher, (void *)5U);
00047     philosopher((void *)1U);
00048 }