SlideShare a Scribd company logo
1 of 11
Download to read offline
#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 );
total_hungry_time += ( msecond() - became_hungry_time );
eat_count++;
draw_eating( n, eat_count );
usleep( 1000L * random_int( MEAN_EAT_TIME ) );
release_chopsticks( n );
draw_thinking( n );
usleep( 1000L * random_int( MEAN_THINK_TIME ) );
}
draw_done( n );
semaphore_wait( mutex );
total_number_of_meals += eat_count;
total_time_spent_waiting += ( total_hungry_time / 1000.0 );
semaphore_signal( mutex );
pthread_exit( NULL );
}
int main( int argc, char *argv[] )
{
pthread_t phil[NUM_PHILOSOPHERS];
int philosopher_data[NUM_PHILOSOPHERS][2];
int duration;
int i;
duration = ( argc > 1 ? atoi( argv[1] ) : 10 );
for ( i = 0; i < NUM_PHILOSOPHERS; i++ )
{
if ( semaphore_create( chopstick[i], 1 ) < 0 ) {
fprintf( stderr, "cannot create chopstick semaphore " );
exit( 1 );
}
}
if ( semaphore_create( screen, 1 ) < 0 ) {
fprintf( stderr, "cannot create screen semaphore " );
exit( 1 );
}
if ( semaphore_create( mutex, 1 ) < 0 ) {
fprintf( stderr, "cannot create mutex semaphore " );
exit( 1 );
}
screen_print();
for ( i = 0; i < NUM_PHILOSOPHERS; i++ )
{
philosopher_data[i][0] = i;
philosopher_data[i][1] = duration;
if ( pthread_create( &phil[i], NULL, (void *(*)(void *)) &philosopher,
&philosopher_data[i] ) != 0 ) {
fprintf( stderr, "cannot create thread for philosopher %d ", i );
exit( 1 );
}
}
for ( i = 0; i < NUM_PHILOSOPHERS; i++ )
{
pthread_join( phil[i], NULL );
}
for ( i = 0; i < NUM_PHILOSOPHERS; i++ )
{
semaphore_release( chopstick[i] );
}
semaphore_release( screen );
semaphore_release( mutex );
position( 13, 1 );
printf( "Total meals served = %d ", total_number_of_meals );
printf( "Average hungry time = %f ",
total_time_spent_waiting / total_number_of_meals );
return 0;
}
Solution
#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 );
total_hungry_time += ( msecond() - became_hungry_time );
eat_count++;
draw_eating( n, eat_count );
usleep( 1000L * random_int( MEAN_EAT_TIME ) );
release_chopsticks( n );
draw_thinking( n );
usleep( 1000L * random_int( MEAN_THINK_TIME ) );
}
draw_done( n );
semaphore_wait( mutex );
total_number_of_meals += eat_count;
total_time_spent_waiting += ( total_hungry_time / 1000.0 );
semaphore_signal( mutex );
pthread_exit( NULL );
}
int main( int argc, char *argv[] )
{
pthread_t phil[NUM_PHILOSOPHERS];
int philosopher_data[NUM_PHILOSOPHERS][2];
int duration;
int i;
duration = ( argc > 1 ? atoi( argv[1] ) : 10 );
for ( i = 0; i < NUM_PHILOSOPHERS; i++ )
{
if ( semaphore_create( chopstick[i], 1 ) < 0 ) {
fprintf( stderr, "cannot create chopstick semaphore " );
exit( 1 );
}
}
if ( semaphore_create( screen, 1 ) < 0 ) {
fprintf( stderr, "cannot create screen semaphore " );
exit( 1 );
}
if ( semaphore_create( mutex, 1 ) < 0 ) {
fprintf( stderr, "cannot create mutex semaphore " );
exit( 1 );
}
screen_print();
for ( i = 0; i < NUM_PHILOSOPHERS; i++ )
{
philosopher_data[i][0] = i;
philosopher_data[i][1] = duration;
if ( pthread_create( &phil[i], NULL, (void *(*)(void *)) &philosopher,
&philosopher_data[i] ) != 0 ) {
fprintf( stderr, "cannot create thread for philosopher %d ", i );
exit( 1 );
}
}
for ( i = 0; i < NUM_PHILOSOPHERS; i++ )
{
pthread_join( phil[i], NULL );
}
for ( i = 0; i < NUM_PHILOSOPHERS; i++ )
{
semaphore_release( chopstick[i] );
}
semaphore_release( screen );
semaphore_release( mutex );
position( 13, 1 );
printf( "Total meals served = %d ", total_number_of_meals );
printf( "Average hungry time = %f ",
total_time_spent_waiting / total_number_of_meals );
return 0;
}

More Related Content

Similar to #include stdio.h #include stdlib.h #include unistd.h .pdf

Similar to #include stdio.h #include stdlib.h #include unistd.h .pdf (20)

135
135135
135
 
Sbaw090623
Sbaw090623Sbaw090623
Sbaw090623
 
I am trying to implement timing on this program and cannot do it. Wh.pdf
I am trying to implement timing on this program and cannot do it. Wh.pdfI am trying to implement timing on this program and cannot do it. Wh.pdf
I am trying to implement timing on this program and cannot do it. Wh.pdf
 
BCSL 058 solved assignment
BCSL 058 solved assignmentBCSL 058 solved assignment
BCSL 058 solved assignment
 
Senior design project code for PPG
Senior design project code for PPGSenior design project code for PPG
Senior design project code for PPG
 
C lab manaual
C lab manaualC lab manaual
C lab manaual
 
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfPCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdf
 
PCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docxPCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docx
 
Vcs16
Vcs16Vcs16
Vcs16
 
Hargun
HargunHargun
Hargun
 
week-23x
week-23xweek-23x
week-23x
 
ADA FILE
ADA FILEADA FILE
ADA FILE
 
Circular queue
Circular queueCircular queue
Circular queue
 
Network lap pgms 7th semester
Network lap pgms 7th semesterNetwork lap pgms 7th semester
Network lap pgms 7th semester
 
Aplikasi menghitung matematika dengan c++
Aplikasi menghitung matematika dengan c++Aplikasi menghitung matematika dengan c++
Aplikasi menghitung matematika dengan c++
 
Zoo management adri jovin
Zoo management  adri jovinZoo management  adri jovin
Zoo management adri jovin
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
ภาษาซี
ภาษาซีภาษาซี
ภาษาซี
 
CODING IN ARDUINO
CODING IN ARDUINOCODING IN ARDUINO
CODING IN ARDUINO
 
Add a 3rd field help that contains a short help string for each of t.pdf
Add a 3rd field help that contains a short help string for each of t.pdfAdd a 3rd field help that contains a short help string for each of t.pdf
Add a 3rd field help that contains a short help string for each of t.pdf
 

More from nipuns1983

0.5164Solution0.5164.pdf
0.5164Solution0.5164.pdf0.5164Solution0.5164.pdf
0.5164Solution0.5164.pdfnipuns1983
 
Thalamus acts as the gateway to the cerebral cortex. It is situated .pdf
  Thalamus acts as the gateway to the cerebral cortex. It is situated .pdf  Thalamus acts as the gateway to the cerebral cortex. It is situated .pdf
Thalamus acts as the gateway to the cerebral cortex. It is situated .pdfnipuns1983
 
ADH causes increased permeability of DCT and collecting tubule to wa.pdf
  ADH causes increased permeability of DCT and collecting tubule to wa.pdf  ADH causes increased permeability of DCT and collecting tubule to wa.pdf
ADH causes increased permeability of DCT and collecting tubule to wa.pdfnipuns1983
 
There are several solutions for treating chronically mentally ill pa.pdf
There are several solutions for treating chronically mentally ill pa.pdfThere are several solutions for treating chronically mentally ill pa.pdf
There are several solutions for treating chronically mentally ill pa.pdfnipuns1983
 
The water is split providing the electrons for PSII, which then exci.pdf
The water is split providing the electrons for PSII, which then exci.pdfThe water is split providing the electrons for PSII, which then exci.pdf
The water is split providing the electrons for PSII, which then exci.pdfnipuns1983
 
The Sarbanes-Oxlet act (SOX) was primarily enacted following the Enr.pdf
The Sarbanes-Oxlet act (SOX) was primarily enacted following the Enr.pdfThe Sarbanes-Oxlet act (SOX) was primarily enacted following the Enr.pdf
The Sarbanes-Oxlet act (SOX) was primarily enacted following the Enr.pdfnipuns1983
 
The integral has a pole at z=-1Integral region is around a circle .pdf
The integral has a pole at z=-1Integral region is around a circle .pdfThe integral has a pole at z=-1Integral region is around a circle .pdf
The integral has a pole at z=-1Integral region is around a circle .pdfnipuns1983
 
SolutionThis encryption scheme is not considered to be a secure o.pdf
SolutionThis encryption scheme is not considered to be a secure o.pdfSolutionThis encryption scheme is not considered to be a secure o.pdf
SolutionThis encryption scheme is not considered to be a secure o.pdfnipuns1983
 
Smart Beta ia a rather elusive term in modern finance sometimes know.pdf
Smart Beta ia a rather elusive term in modern finance sometimes know.pdfSmart Beta ia a rather elusive term in modern finance sometimes know.pdf
Smart Beta ia a rather elusive term in modern finance sometimes know.pdfnipuns1983
 
Ques-1 What is the differential diagnosis of this patients infectin.pdf
Ques-1 What is the differential diagnosis of this patients infectin.pdfQues-1 What is the differential diagnosis of this patients infectin.pdf
Ques-1 What is the differential diagnosis of this patients infectin.pdfnipuns1983
 
package employeeType.employee;public abstract class Employee {  .pdf
package employeeType.employee;public abstract class Employee {  .pdfpackage employeeType.employee;public abstract class Employee {  .pdf
package employeeType.employee;public abstract class Employee {  .pdfnipuns1983
 
Option 1Project management software Project management software .pdf
Option 1Project management software Project management software .pdfOption 1Project management software Project management software .pdf
Option 1Project management software Project management software .pdfnipuns1983
 
import java.util.Scanner;public class InputIntegers{public sta.pdf
import java.util.Scanner;public class InputIntegers{public sta.pdfimport java.util.Scanner;public class InputIntegers{public sta.pdf
import java.util.Scanner;public class InputIntegers{public sta.pdfnipuns1983
 
The main drawback of Troutons rule is that it i.pdf
                     The main drawback of Troutons rule is that it i.pdf                     The main drawback of Troutons rule is that it i.pdf
The main drawback of Troutons rule is that it i.pdfnipuns1983
 
Solid to liquid, or liquid to gas change absorbs .pdf
                     Solid to liquid, or liquid to gas change absorbs .pdf                     Solid to liquid, or liquid to gas change absorbs .pdf
Solid to liquid, or liquid to gas change absorbs .pdfnipuns1983
 
RNase P catalyzes the Mg2+-dependent 5-maturati.pdf
                     RNase P catalyzes the Mg2+-dependent 5-maturati.pdf                     RNase P catalyzes the Mg2+-dependent 5-maturati.pdf
RNase P catalyzes the Mg2+-dependent 5-maturati.pdfnipuns1983
 
pH of a solution is directly proportional to mola.pdf
                     pH of a solution is directly proportional to mola.pdf                     pH of a solution is directly proportional to mola.pdf
pH of a solution is directly proportional to mola.pdfnipuns1983
 
Option - D is correct !! .pdf
                     Option - D is correct !!                         .pdf                     Option - D is correct !!                         .pdf
Option - D is correct !! .pdfnipuns1983
 
n = number present before orbital =3 l= 0 for s, .pdf
                     n = number present before orbital =3 l= 0 for s, .pdf                     n = number present before orbital =3 l= 0 for s, .pdf
n = number present before orbital =3 l= 0 for s, .pdfnipuns1983
 
nitro methane is a polar compound plus it has nit.pdf
                     nitro methane is a polar compound plus it has nit.pdf                     nitro methane is a polar compound plus it has nit.pdf
nitro methane is a polar compound plus it has nit.pdfnipuns1983
 

More from nipuns1983 (20)

0.5164Solution0.5164.pdf
0.5164Solution0.5164.pdf0.5164Solution0.5164.pdf
0.5164Solution0.5164.pdf
 
Thalamus acts as the gateway to the cerebral cortex. It is situated .pdf
  Thalamus acts as the gateway to the cerebral cortex. It is situated .pdf  Thalamus acts as the gateway to the cerebral cortex. It is situated .pdf
Thalamus acts as the gateway to the cerebral cortex. It is situated .pdf
 
ADH causes increased permeability of DCT and collecting tubule to wa.pdf
  ADH causes increased permeability of DCT and collecting tubule to wa.pdf  ADH causes increased permeability of DCT and collecting tubule to wa.pdf
ADH causes increased permeability of DCT and collecting tubule to wa.pdf
 
There are several solutions for treating chronically mentally ill pa.pdf
There are several solutions for treating chronically mentally ill pa.pdfThere are several solutions for treating chronically mentally ill pa.pdf
There are several solutions for treating chronically mentally ill pa.pdf
 
The water is split providing the electrons for PSII, which then exci.pdf
The water is split providing the electrons for PSII, which then exci.pdfThe water is split providing the electrons for PSII, which then exci.pdf
The water is split providing the electrons for PSII, which then exci.pdf
 
The Sarbanes-Oxlet act (SOX) was primarily enacted following the Enr.pdf
The Sarbanes-Oxlet act (SOX) was primarily enacted following the Enr.pdfThe Sarbanes-Oxlet act (SOX) was primarily enacted following the Enr.pdf
The Sarbanes-Oxlet act (SOX) was primarily enacted following the Enr.pdf
 
The integral has a pole at z=-1Integral region is around a circle .pdf
The integral has a pole at z=-1Integral region is around a circle .pdfThe integral has a pole at z=-1Integral region is around a circle .pdf
The integral has a pole at z=-1Integral region is around a circle .pdf
 
SolutionThis encryption scheme is not considered to be a secure o.pdf
SolutionThis encryption scheme is not considered to be a secure o.pdfSolutionThis encryption scheme is not considered to be a secure o.pdf
SolutionThis encryption scheme is not considered to be a secure o.pdf
 
Smart Beta ia a rather elusive term in modern finance sometimes know.pdf
Smart Beta ia a rather elusive term in modern finance sometimes know.pdfSmart Beta ia a rather elusive term in modern finance sometimes know.pdf
Smart Beta ia a rather elusive term in modern finance sometimes know.pdf
 
Ques-1 What is the differential diagnosis of this patients infectin.pdf
Ques-1 What is the differential diagnosis of this patients infectin.pdfQues-1 What is the differential diagnosis of this patients infectin.pdf
Ques-1 What is the differential diagnosis of this patients infectin.pdf
 
package employeeType.employee;public abstract class Employee {  .pdf
package employeeType.employee;public abstract class Employee {  .pdfpackage employeeType.employee;public abstract class Employee {  .pdf
package employeeType.employee;public abstract class Employee {  .pdf
 
Option 1Project management software Project management software .pdf
Option 1Project management software Project management software .pdfOption 1Project management software Project management software .pdf
Option 1Project management software Project management software .pdf
 
import java.util.Scanner;public class InputIntegers{public sta.pdf
import java.util.Scanner;public class InputIntegers{public sta.pdfimport java.util.Scanner;public class InputIntegers{public sta.pdf
import java.util.Scanner;public class InputIntegers{public sta.pdf
 
The main drawback of Troutons rule is that it i.pdf
                     The main drawback of Troutons rule is that it i.pdf                     The main drawback of Troutons rule is that it i.pdf
The main drawback of Troutons rule is that it i.pdf
 
Solid to liquid, or liquid to gas change absorbs .pdf
                     Solid to liquid, or liquid to gas change absorbs .pdf                     Solid to liquid, or liquid to gas change absorbs .pdf
Solid to liquid, or liquid to gas change absorbs .pdf
 
RNase P catalyzes the Mg2+-dependent 5-maturati.pdf
                     RNase P catalyzes the Mg2+-dependent 5-maturati.pdf                     RNase P catalyzes the Mg2+-dependent 5-maturati.pdf
RNase P catalyzes the Mg2+-dependent 5-maturati.pdf
 
pH of a solution is directly proportional to mola.pdf
                     pH of a solution is directly proportional to mola.pdf                     pH of a solution is directly proportional to mola.pdf
pH of a solution is directly proportional to mola.pdf
 
Option - D is correct !! .pdf
                     Option - D is correct !!                         .pdf                     Option - D is correct !!                         .pdf
Option - D is correct !! .pdf
 
n = number present before orbital =3 l= 0 for s, .pdf
                     n = number present before orbital =3 l= 0 for s, .pdf                     n = number present before orbital =3 l= 0 for s, .pdf
n = number present before orbital =3 l= 0 for s, .pdf
 
nitro methane is a polar compound plus it has nit.pdf
                     nitro methane is a polar compound plus it has nit.pdf                     nitro methane is a polar compound plus it has nit.pdf
nitro methane is a polar compound plus it has nit.pdf
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Recently uploaded (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

#include stdio.h #include stdlib.h #include unistd.h .pdf

  • 1. #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 )
  • 2. { 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 );
  • 3. } 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;
  • 4. 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 ); total_hungry_time += ( msecond() - became_hungry_time ); eat_count++; draw_eating( n, eat_count ); usleep( 1000L * random_int( MEAN_EAT_TIME ) ); release_chopsticks( n ); draw_thinking( n ); usleep( 1000L * random_int( MEAN_THINK_TIME ) ); } draw_done( n ); semaphore_wait( mutex ); total_number_of_meals += eat_count; total_time_spent_waiting += ( total_hungry_time / 1000.0 ); semaphore_signal( mutex ); pthread_exit( NULL ); } int main( int argc, char *argv[] ) { pthread_t phil[NUM_PHILOSOPHERS]; int philosopher_data[NUM_PHILOSOPHERS][2]; int duration; int i; duration = ( argc > 1 ? atoi( argv[1] ) : 10 ); for ( i = 0; i < NUM_PHILOSOPHERS; i++ ) {
  • 5. if ( semaphore_create( chopstick[i], 1 ) < 0 ) { fprintf( stderr, "cannot create chopstick semaphore " ); exit( 1 ); } } if ( semaphore_create( screen, 1 ) < 0 ) { fprintf( stderr, "cannot create screen semaphore " ); exit( 1 ); } if ( semaphore_create( mutex, 1 ) < 0 ) { fprintf( stderr, "cannot create mutex semaphore " ); exit( 1 ); } screen_print(); for ( i = 0; i < NUM_PHILOSOPHERS; i++ ) { philosopher_data[i][0] = i; philosopher_data[i][1] = duration; if ( pthread_create( &phil[i], NULL, (void *(*)(void *)) &philosopher, &philosopher_data[i] ) != 0 ) { fprintf( stderr, "cannot create thread for philosopher %d ", i ); exit( 1 ); } } for ( i = 0; i < NUM_PHILOSOPHERS; i++ ) { pthread_join( phil[i], NULL ); } for ( i = 0; i < NUM_PHILOSOPHERS; i++ ) { semaphore_release( chopstick[i] ); } semaphore_release( screen ); semaphore_release( mutex ); position( 13, 1 ); printf( "Total meals served = %d ", total_number_of_meals );
  • 6. printf( "Average hungry time = %f ", total_time_spent_waiting / total_number_of_meals ); return 0; } Solution #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 );
  • 7. 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 ); }
  • 8. 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 );
  • 9. 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 ); total_hungry_time += ( msecond() - became_hungry_time ); eat_count++; draw_eating( n, eat_count ); usleep( 1000L * random_int( MEAN_EAT_TIME ) ); release_chopsticks( n ); draw_thinking( n ); usleep( 1000L * random_int( MEAN_THINK_TIME ) ); } draw_done( n ); semaphore_wait( mutex ); total_number_of_meals += eat_count; total_time_spent_waiting += ( total_hungry_time / 1000.0 ); semaphore_signal( mutex ); pthread_exit( NULL ); } int main( int argc, char *argv[] ) { pthread_t phil[NUM_PHILOSOPHERS];
  • 10. int philosopher_data[NUM_PHILOSOPHERS][2]; int duration; int i; duration = ( argc > 1 ? atoi( argv[1] ) : 10 ); for ( i = 0; i < NUM_PHILOSOPHERS; i++ ) { if ( semaphore_create( chopstick[i], 1 ) < 0 ) { fprintf( stderr, "cannot create chopstick semaphore " ); exit( 1 ); } } if ( semaphore_create( screen, 1 ) < 0 ) { fprintf( stderr, "cannot create screen semaphore " ); exit( 1 ); } if ( semaphore_create( mutex, 1 ) < 0 ) { fprintf( stderr, "cannot create mutex semaphore " ); exit( 1 ); } screen_print(); for ( i = 0; i < NUM_PHILOSOPHERS; i++ ) { philosopher_data[i][0] = i; philosopher_data[i][1] = duration; if ( pthread_create( &phil[i], NULL, (void *(*)(void *)) &philosopher, &philosopher_data[i] ) != 0 ) { fprintf( stderr, "cannot create thread for philosopher %d ", i ); exit( 1 ); } } for ( i = 0; i < NUM_PHILOSOPHERS; i++ ) { pthread_join( phil[i], NULL ); } for ( i = 0; i < NUM_PHILOSOPHERS; i++ ) {
  • 11. semaphore_release( chopstick[i] ); } semaphore_release( screen ); semaphore_release( mutex ); position( 13, 1 ); printf( "Total meals served = %d ", total_number_of_meals ); printf( "Average hungry time = %f ", total_time_spent_waiting / total_number_of_meals ); return 0; }