|
我写的一个消费者生产者程序老是有问题,一个错误该不了,大家看看呀。帮我以下。
/*利用环绕缓冲区下的信号灯机制控制实现生产者和消费者问题*/
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<sys/ipc.h>
#include<sys/types.h>
#include<time.h>
#include<sys/sem.h>
#include<pthread.h>
#include<semaphore.h>
#define nbuff 10
#define sem_mutex "mutex"
#define sem_nempty "nempty"
#define sem_nstored "nstored"
int nitems;
struct {
int buff[nbuff];
sem_t *mutex,*nempty,*nstored;
}shared;
void *produce(void*),*consume(void*);
int main(int argc,char **argv)
{
pthread_t tid_produce,tid_consume;
int mutex,nempty,nstored;
if(argc!=2)
{
puts("usage:prodcons1<#items>");
exit(EXIT_FAILURE);
}
nitems=atoi(argv[1]);
/*创建三个信号灯其中MUTEX用来保护两个临界区
*NEMPTY统计空槽数NSTORED用来统计填满的槽数*/
sem.mutex=Sem_init(&shared.mutex,0,1);
sem.nempty=Sem_init(&shared.nempty,0,nbuff);
sem.nstored=Sem_init(&shared.nstored,0,0);
/*创建一个生产者和消费者线程*/
Set_concurrency(2);
pthread_create(&tid_produce,NULL,(void*)produce,NULL);
pthread_create(&tid_consume,NULL,(void*)consume,NULL);
/*挂起当前进程*/
pthread_join(tid_produce,NULL);
pthread_join(tid_produce,NULL);
/*删除信号灯*/
Sem_unlink(sem_mutex);
Sem_unlink(sem_nempty);
Sem_unlink(sem_nstored);
exit(EXIT_SUCCESS);
}
/*生产者和消费者的函数体*/
void *produce(void *arg)
{
int i;
for(i=0;i<nitems;i++)
{
Sem_wait(shared.nempty);
Sem_wait(shared.mutex);
shared.buff[i%nbuff]=i;
Sem_post(shared.mutex);
Sem_post(shared.nstored);
}
return(NULL);
}
void*consume(void*arg)
{
int i;
for(i=0;i<nitems;i++)
{
Sem_wait(shared.nstored);
Sem_wait(shared.mutex);
if(shared.buff[i%nbuff]!=i)
printf("buff[%d]=%d\n",i,shared.buff[i%nbuff]);
Sem_post(shared.mutex);
Sem_post(shared.nempty);
}
return(NULL);
} |
|