#include
#include
#include
#include
#include
#include \"msecond.h\"
#include \"random_int.h\"
float total_time_spent_waiting = 0.0;
int total_number_of_meals = 0;
#define semaphore_create(s,v) sem_init( &s, 0, v )
#define semaphore_wait(s) sem_wait( &s )
#define semaphore_signal(s) sem_post( &s )
#define semaphore_release(s) sem_destroy( &s )
typedef sem_t semaphore;
semaphore chopstick[NUM_PHILOSOPHERS];
semaphore screen;
semaphore mutex;
int screen_row[NUM_PHILOSOPHERS] = { 6, 2, 2, 6, 10 };
int screen_col[NUM_PHILOSOPHERS] = { 31, 36, 44, 49, 40 };
int chopstick_row[5] = { 9, 4, 3, 4, 9 };
int chopstick_col[5] = { 35, 33, 40, 47, 45 };
char chopstick_sym[5] = { \'/\', \'\\\\\', \'|\', \'/\', \'\\\\\' };
for ( i = 0; i < NUM_PHILOSOPHERS; i++ )
{
position( screen_row[i], screen_col[i] );
printf( \"%d\", i );
position( screen_row[i] + 1, screen_col[i] - 1 );
printf( \"(%d)\", 0 );
position( chopstick_row[i], chopstick_col[i] );
printf( \"%c\", chopstick_sym[i] );
}
position_flush( 13, 1 );
}
void draw_thinking( int n )
{
semaphore_wait( screen );
position( screen_row[n], screen_col[n] );
position_flush( 13, 1 );
semaphore_signal( screen );
}
void draw_hungry( int n )
{
semaphore_wait( screen );
position( screen_row[n], screen_col[n] );
position_flush( 13, 1 );
semaphore_signal( screen );
}
void draw_eating( int n, int eat_count )
{
semaphore_wait( screen );
position( screen_row[n], screen_col[n] );
position( screen_row[n] + 1, screen_col[n] - 1 );
printf( \"(%d)\", eat_count );
position_flush( 13, 1 );
semaphore_signal( screen );
}
void draw_chopstick_up( int n )
{
semaphore_wait( screen );
position( chopstick_row[n], chopstick_col[n] );
printf( \"%c\", \' \' );
position_flush( 13, 1 );
semaphore_signal( screen );
}
void draw_chopstick_down( int n )
{
semaphore_wait( screen );
position( chopstick_row[n], chopstick_col[n] );
position_flush( 13, 1 );
semaphore_signal( screen );
}
void draw_done( int n )
{
semaphore_wait( screen );
position( screen_row[n], screen_col[n] );
printf( \"D\" );
position_flush( 13, 1 );
semaphore_signal( screen );
}
void chopsticks( int n )
{
if ( n % 2 == 0 ) {
semaphore_wait( chopstick[(n+1) % NUM_PHILOSOPHERS] );
draw_chopstick_up( (n+1) % NUM_PHILOSOPHERS );
semaphore_wait( chopstick[n] );
draw_chopstick_up( n );
} else {
semaphore_wait( chopstick[n] );
draw_chopstick_up( n );
semaphore_wait( chopstick[(n+1) % NUM_PHILOSOPHERS] );
draw_chopstick_up( (n+1) % NUM_PHILOSOPHERS );
}
}
void release_chopsticks( int n )
{
draw_chopstick_down( n );
semaphore_signal( chopstick[n] );
draw_chopstick_down( (n+1) % NUM_PHILOSOPHERS );
semaphore_signal( chopstick[(n+1) % NUM_PHILOSOPHERS] );
}
void philosopher( int *philosopher_data )
{
int start_time;
int eat_count = 0;
int total_hungry_time = 0;
int became_hungry_time;
int n = philosopher_data[0];
int duration = philosopher_data[1];
start_time = msecond();
while( msecond() - start_time < duration * 1000 )
{
became_hungry_time = msecond();
draw_hungry( n );
chopsticks( n );
t.