DP_AST3

Dependencies:   TextLCD mbed-rtos mbed

main.cpp

Committer:
lucastai
Date:
2015-09-26
Revision:
1:21958cb07fb4
Parent:
0:65611c1179b6
Child:
2:8bab2e3d3005

File content as of revision 1:21958cb07fb4:

#include "mbed.h"
#include "TextLCD.h"
#include "Mutex.h"
#include "rtos.h"
#include "Thread.h"
using namespace rtos;

//Define LCD 
TextLCD lcd(p15, p16, p17, p18, p19, p20, TextLCD::LCD20x4); // rs, e, d4-d7

//Individual Mutex for each chopstick
Mutex chopsticks[5];

// Eating routine
void eat(const int* phil) {
    // All chopsticks (0-4) are behind an individual mutex, and must be aquired from lowest to highest
    // Each philosopher picks up the chopsticks to his left (index - 1) and right (index % 5), or waits for one
    chopsticks[(int)phil - 1].lock();
    chopsticks[(int)phil % 5].lock();
    
    //The eating period is between 1000 and 2000 ms
    int eatPeriod = rand()%1000 + 1000;
    
    // we locate the part of the LCD 
    lcd.locate((int)phil,0);
    lcd.putc((int)phil + 48);
    
    // The thread waits while the philosopher is eating
    Thread::wait(eatPeriod);
    
    //After eating, the philosopher puts down the chopsticks 
    lcd.locate((int)phil,0);
    lcd.printf(" ");
    chopsticks[(int)phil - 1].unlock();
    chopsticks[(int)phil % 5].unlock();
}

// General thread behavioral routine, eating and waiting (philosophizing)
void philosophizeAndEat(void const *args) {
    while (true) {
        //Decide a time between 5-10 seconds between eating requests
        int waitPeriod = rand()%5000 + 5000;
        
        //Performing the eating routine
        eat((const int*)args); 
        
        // wait until time elapses to eat again
        Thread::wait(waitPeriod);
    }
}

// setup routine, create all philosophers
int main() {
    // Initialize 5 philosopher threads with IDs
    Thread t3(philosophizeAndEat, (void *)3);
    Thread t2(philosophizeAndEat, (void *)2);
    Thread t4(philosophizeAndEat, (void *)4);
    Thread t5(philosophizeAndEat, (void *)5);
    philosophizeAndEat((void *)1);
}