Lucas Tai-MacArthur / Mbed 2 deprecated DiningPhilosophers

Dependencies:   TextLCD mbed-rtos mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "TextLCD.h"
00002 #include "Mutex.h"
00003 #include "rtos.h"
00004 #include "Thread.h"
00005 using namespace rtos;
00006 
00007 //Define LCD 
00008 TextLCD lcd(p15, p16, p17, p18, p19, p20, TextLCD::LCD20x4); // rs, e, d4-d7
00009 
00010 //Individual Mutex for each chopstick
00011 Mutex chopsticks[5];
00012 
00013 // Eating routine
00014 void eat(const int* phil) {
00015     // All chopsticks (0-4) are behind an individual mutex
00016     // Each philosopher picks up the even chopstick of the left right pair first, ie. they alternate between which
00017     // they pick up first based on their ID
00018     
00019     if((int)phil % 2 == 0){    
00020         chopsticks[(int)phil % 5].lock();
00021         chopsticks[(int)phil - 1].lock();
00022     }else{
00023         chopsticks[(int)phil - 1].lock();
00024         chopsticks[(int)phil % 5].lock();
00025     }
00026            
00027     // we locate the part of the LCD, put the char to signifiy the philosopher eating
00028     lcd.locate((int)phil,0);
00029     lcd.putc((int)phil + 48);
00030     
00031     //The eating period is between 1000 and 2000 ms
00032     int eatPeriod = rand()%1000 + 1000;
00033     // The thread waits while the philosopher is eating
00034     Thread::wait(eatPeriod);
00035     
00036     //After eating, the philosopher puts down the chopsticks and clears himself from the LCD
00037     lcd.locate((int)phil,0);
00038     lcd.printf(" ");
00039     chopsticks[(int)phil - 1].unlock();
00040     chopsticks[(int)phil % 5].unlock();
00041 }
00042 
00043 // General thread behavioral routine, eating and waiting (philosophizing)
00044 void philosophizeAndEat(void const *args) {
00045     while (true) {
00046         //Decide a time between 5-10 seconds between eating requests
00047         int waitPeriod = rand()%5000 + 5000;
00048         // wait until time elapses to eat again
00049         Thread::wait(waitPeriod);
00050         
00051         //Performing the eating routine
00052         eat((const int*)args); 
00053     }
00054 }
00055 
00056 // setup routine, create all philosophers
00057 int main() {
00058     // Initialize 5 philosopher threads with IDs
00059     Thread t3(philosophizeAndEat, (void *)3);
00060     Thread t2(philosophizeAndEat, (void *)2);
00061     Thread t4(philosophizeAndEat, (void *)4);
00062     Thread t5(philosophizeAndEat, (void *)5);
00063     philosophizeAndEat((void *)1);
00064 }