Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: TextLCD mbed-rtos mbed
Revision 2:8bab2e3d3005, committed 2015-09-28
- Comitter:
- lucastai
- Date:
- Mon Sep 28 15:38:35 2015 +0000
- Parent:
- 1:21958cb07fb4
- Commit message:
- 3rd;
Changed in this revision
| main.cpp | Show annotated file Show diff for this revision Revisions of this file |
--- a/main.cpp Sat Sep 26 21:48:56 2015 +0000
+++ b/main.cpp Mon Sep 28 15:38:35 2015 +0000
@@ -1,4 +1,3 @@
-#include "mbed.h"
#include "TextLCD.h"
#include "Mutex.h"
#include "rtos.h"
@@ -13,22 +12,28 @@
// 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();
+ // All chopsticks (0-4) are behind an individual mutex
+ // Each philosopher picks up the even chopstick of the left right pair first, ie. they alternate between which
+ // they pick up first based on their ID
+
+ if((int)phil % 2 == 0){
+ chopsticks[(int)phil % 5].lock();
+ chopsticks[(int)phil - 1].lock();
+ }else{
+ chopsticks[(int)phil - 1].lock();
+ chopsticks[(int)phil % 5].lock();
+ }
+
+ // we locate the part of the LCD, put the char to signifiy the philosopher eating
+ lcd.locate((int)phil,0);
+ lcd.putc((int)phil + 48);
//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
+ //After eating, the philosopher puts down the chopsticks and clears himself from the LCD
lcd.locate((int)phil,0);
lcd.printf(" ");
chopsticks[(int)phil - 1].unlock();
@@ -40,12 +45,11 @@
while (true) {
//Decide a time between 5-10 seconds between eating requests
int waitPeriod = rand()%5000 + 5000;
+ // wait until time elapses to eat again
+ Thread::wait(waitPeriod);
//Performing the eating routine
eat((const int*)args);
-
- // wait until time elapses to eat again
- Thread::wait(waitPeriod);
}
}