00001
00002
00003
00004
00005
00006
00007
00008 #include <utility/ostream.h>
00009 #include <thread.h>
00010 #include <mutex.h>
00011 #include <alarm.h>
00012 #include <display.h>
00013
00014 __USING_SYS
00015
00016 const int iterations = 10;
00017
00018 Thread * m;
00019 Thread * phil[5];
00020 Mutex * chopstick[5];
00021
00022 OStream cout;
00023
00024 int philosopher(int n, int l, int c)
00025 {
00026 Display display;
00027
00028
00029
00030
00031 int first = (n < 4)? n : 0;
00032 int second = (n < 4)? n + 1 : 4;
00033
00034 for(int i = iterations; i > 0; i--) {
00035 display.position(l, c);
00036 cout << "thinking";
00037 Alarm::delay(1000000);
00038
00039 chopstick[first]->lock();
00040 chopstick[second]->lock();
00041 display.position(l, c);
00042 cout << " eating ";
00043 Alarm::delay(500000);
00044 chopstick[first]->unlock();
00045 chopstick[second]->unlock();
00046 }
00047
00048 return(iterations);
00049 }
00050
00051 int main()
00052 {
00053 Display display;
00054
00055 display.clear();
00056 cout << "The Philosopher's Dinner:\n";
00057
00058 for(int i = 0; i < 5; i++)
00059 chopstick[i] = new Mutex;
00060
00061 phil[0] = new Thread(&philosopher, 0, 5, 32);
00062 phil[1] = new Thread(&philosopher, 1, 10, 44);
00063 phil[2] = new Thread(&philosopher, 2, 16, 39);
00064 phil[3] = new Thread(&philosopher, 3, 16, 24);
00065 phil[4] = new Thread(&philosopher, 4, 10, 20);
00066
00067 cout << "Philosophers are alife and hungry!\n";
00068
00069 cout << "The dinner is served!\n";
00070 display.position(7, 44);
00071 cout << '/';
00072 display.position(13, 44);
00073 cout << '\\';
00074 display.position(16, 35);
00075 cout << '|';
00076 display.position(13, 27);
00077 cout << '/';
00078 display.position(7, 27);
00079 cout << '\\';
00080
00081 for(int i = 0; i < 5; i++) {
00082 int ret = phil[i]->join();
00083 display.position(20 + i, 0);
00084 cout << "Philosopher " << i << " ate " << ret << " times \n";
00085 }
00086
00087 cout << "The end!\n";
00088
00089 return 0;
00090 }