#include
#include
#include
#include
#include
#include
#include
#include
//杀掉程序时记得删除/dev/shm/process_cond 文件。否则你试试奇怪现象
//删除/dev/shm/process_cond 没有ftruncate(fd, sizeof(s_share));这句会出现总线错误 (核心已转储)
//gcc process_cond.c -lpthread -lrt
pthread_t tid_produce,tid_produce1,tid_consume;
pid_t pid;
int fd;
int rtn;
typedef struct s_share{
pthread_mutex_t mutex;
pthread_mutexattr_t ma;
pthread_cond_t cond;
pthread_condattr_t ca;
int num_ptr;
}*ps_shared,s_share;
ps_shared shared=NULL;
void * produce(void*);
void * produce1(void*);
void * consume(void*);
int main(void)
{
//fd = open("/tmp/process_cond",O_RDWR|O_CREAT);
fd = shm_open("process_cond", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if(0 > fd){
printf("open error\n");
}
ftruncate(fd, sizeof(s_share));
shared = mmap(NULL,sizeof(struct s_share),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if (shared == MAP_FAILED) {
printf("error map\n");
return 0;
}
close(fd);
pthread_mutexattr_init(&(shared->ma));
rtn = pthread_mutexattr_setpshared( &(shared->ma), PTHREAD_PROCESS_SHARED );
printf("rtn pthread_mutexattr_setpshared == %d\n",rtn);
rtn = pthread_mutex_init(&(shared->mutex),&(shared->ma));
printf("rtn pthread_mutex_init==%d\n",rtn);
pthread_condattr_init(&(shared->ca));
pthread_condattr_setpshared( &(shared->ca), PTHREAD_PROCESS_SHARED );
pthread_cond_init(&(shared->cond),&(shared->ca));
printf("woddo\n");
if((pid = fork()) < 0){
printf("fork 1 error\n");
}
else if ( 0 == pid){
produce(NULL);
}
if((pid = fork()) < 0){
printf("fork 2 error\n");
}
else if ( 0 == pid){
produce1(NULL);
}
if((pid = fork()) < 0){
printf("fork 3 error\n");
}
else if ( 0 == pid){
consume(NULL);
}
while(1);
}
void * produce(void *arg)
{
for(;;)
{
pthread_mutex_lock(&(shared->mutex));
if(shared->num_ptr >= 10){
pthread_cond_wait(&(shared->cond),&(shared->mutex));
}
shared->num_ptr++;
printf("produce shared.num == %d\n",shared->num_ptr);
pthread_mutex_unlock(&(shared->mutex));
sleep(1);
}
}
void * produce1(void *arg)
{
for(;;)
{
pthread_mutex_lock(&(shared->mutex));
if(shared->num_ptr >= 10){
pthread_cond_wait(&(shared->cond),&(shared->mutex));
}
shared->num_ptr ++;
printf("produce1 shared.num == %d\n",shared->num_ptr);
pthread_mutex_unlock(&(shared->mutex));
sleep(1);
}
}
void * consume(void *arg)
{
for(;;)
{
pthread_mutex_lock(&(shared->mutex));
if(shared->num_ptr <= 0){
//pthread_cond_signal(&(shared->cond));
pthread_cond_broadcast(&(shared->cond));
}
else{
shared->num_ptr --;
}
printf("consume shared.num == %d\n",shared->num_ptr);
pthread_mutex_unlock(&(shared->mutex));
sleep(2);
}
}
阅读(3385) | 评论(0) | 转发(0) |