单个生产者,单个消费者问题
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<semaphore.h>
#include<pthread.h>
#define NBUF 10
struct
{
int buf[NBUF];
sem_t mutex,nempty,nstored;
}shared;
void* produce(void*);
void* consume(void*);
int nitems;
int main(int argc,char** argv)
{
pthread_t tid_produce,tid_consume;
if(argc!=2)
{
fprintf(stderr,"usage:prodcons1<#items>\n");
exit(1);
}
nitems=atoi(argv[1]);
sem_init(&shared.mutex,0,1);
sem_init(&shared.nempty,0,NBUF);
sem_init(&shared.nstored,0,0);
pthread_create(&tid_produce,NULL,produce,NULL);
pthread_create(&tid_consume,NULL,consume,NULL);
pthread_join(tid_produce,NULL);
pthread_join(tid_consume,NULL);
sem_destroy(&shared.mutex);
sem_destroy(&shared.nempty);
sem_destroy(&shared.nstored);
exit(0);
}
void* produce(void* arg)
{
int i;
for(i=0;i<nitems;i++)
{
sem_wait(&shared.nempty);
sem_wait(&shared.mutex);
shared.buf[i%NBUF]=i;
sem_post(&shared.mutex);
sem_post(&shared.nstored);
}
return NULL;
}
void* consume(void* arg)
{
int i;
for(i