//
pe.c
// 哲学家吃空心粉的问题
// Copyright 2011 shiweifu <shiweifu@126.com>
//
#define _REENTRANT
#include < stdio.h >
#include < unistd.h >
#include < stdlib.h >
#include < string .h >
#include < semaphore.h >
#include < pthread.h >
#define STR_MAX 256
typedef struct philosophy {
char name[STR_MAX];
sem_t * left;
sem_t * right;
char is_stop;
} philosophy;
void * thread_function( void * arg);
int main( int argc, char ** argv) {
int i = 0 ;
// 五只悲剧的筷子
sem_t sems[ 5 ];
// 五个NC哲学家
philosophy philers[ 5 ];
pthread_t threads[ 5 ];
int res = 0 ;
char tmp[ 255 ] = { 0 };
for (; i < 5 ; i ++ ) {
philers[i].left = & sems[i];
philers[i].right = & sems[i];
if (i == 4 ) {
philers[i].left = & sems[ 0 ];
}
philers[i].is_stop = 0 ;
sprintf(tmp, " NC %d " ,i);
strncpy(philers[i].name,tmp, 255 );
}
for (i = 0 ; i < 5 ; i ++ ) {
sem_init( & sems[i], 0 , 10 );
res = pthread_create( & threads[i],NULL,thread_function, & philers[i]);
if (res != 0 ) {
perror( " 创建线程出错啦... " );
}
}
// 给这群吃货吃20秒
sleep( 20 );
for (i = 0 ; i < 5 ; i ++ ) {
philers[i].is_stop = 1 ;
pthread_join(threads[i],NULL);
}
for (i = 0 ; i < 5 ; i ++ ) {
sem_destroy( & sems[i]);
}
exit(EXIT_SUCCESS);
}
void * thread_function( void * arg) {
philosophy * p = arg;
while ( 1 ) {
if (sem_trywait(p -> left) == 0 ) {
if (sem_trywait(p -> right) == 0 ) {
printf( " 红烧翅膀真好吃,我是%s\n " ,p -> name);
sem_post(p -> left);
sem_post(p -> right);
sleep( 1 );
} else {
sem_post(p -> left);
}
}
if (p -> is_stop == 1 ) {
break ;
}
}
pthread_exit(NULL);
}
// 哲学家吃空心粉的问题
// Copyright 2011 shiweifu <shiweifu@126.com>
//
#define _REENTRANT
#include < stdio.h >
#include < unistd.h >
#include < stdlib.h >
#include < string .h >
#include < semaphore.h >
#include < pthread.h >
#define STR_MAX 256
typedef struct philosophy {
char name[STR_MAX];
sem_t * left;
sem_t * right;
char is_stop;
} philosophy;
void * thread_function( void * arg);
int main( int argc, char ** argv) {
int i = 0 ;
// 五只悲剧的筷子
sem_t sems[ 5 ];
// 五个NC哲学家
philosophy philers[ 5 ];
pthread_t threads[ 5 ];
int res = 0 ;
char tmp[ 255 ] = { 0 };
for (; i < 5 ; i ++ ) {
philers[i].left = & sems[i];
philers[i].right = & sems[i];
if (i == 4 ) {
philers[i].left = & sems[ 0 ];
}
philers[i].is_stop = 0 ;
sprintf(tmp, " NC %d " ,i);
strncpy(philers[i].name,tmp, 255 );
}
for (i = 0 ; i < 5 ; i ++ ) {
sem_init( & sems[i], 0 , 10 );
res = pthread_create( & threads[i],NULL,thread_function, & philers[i]);
if (res != 0 ) {
perror( " 创建线程出错啦... " );
}
}
// 给这群吃货吃20秒
sleep( 20 );
for (i = 0 ; i < 5 ; i ++ ) {
philers[i].is_stop = 1 ;
pthread_join(threads[i],NULL);
}
for (i = 0 ; i < 5 ; i ++ ) {
sem_destroy( & sems[i]);
}
exit(EXIT_SUCCESS);
}
void * thread_function( void * arg) {
philosophy * p = arg;
while ( 1 ) {
if (sem_trywait(p -> left) == 0 ) {
if (sem_trywait(p -> right) == 0 ) {
printf( " 红烧翅膀真好吃,我是%s\n " ,p -> name);
sem_post(p -> left);
sem_post(p -> right);
sleep( 1 );
} else {
sem_post(p -> left);
}
}
if (p -> is_stop == 1 ) {
break ;
}
}
pthread_exit(NULL);
}