单生产者单消费者
1.有名信号量的单生产者单消费者
-
#include "../unipc.h"
-
-
#define NBUFF 10
-
#define SEM_MUTEX "mutex"
-
#define SEM_NEMPTY "nempty"
-
#define SEM_NSTORED "nstored"
-
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
-
int nitems;
-
-
struct {
-
int buff[NBUFF];
-
sem_t *mutex,*nempty,*nstored;
-
} shared;
-
-
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(i != shared.buff[i%NBUFF]) {
-
printf("i = %d,buff[%d]=%d\n",i,i,shared.buff[i]);
-
}
-
sem_post(shared.mutex);
-
sem_post(shared.nempty);
-
}
-
return NULL;
-
}
-
-
int main(int argc ,char *argv[])
-
{
-
pthread_t ptid_produce,ptid_consume;
-
-
if(argc != 2 ) {
-
printf("usage produce1 <#items>\n");
-
return -1;
-
}
-
nitems = atoi(argv[1]);
-
-
shared.mutex = sem_open(SEM_MUTEX,O_CREAT|O_EXCL,FILE_MODE,1);
-
shared.nempty = sem_open(SEM_NEMPTY,O_CREAT|O_EXCL,FILE_MODE,NBUFF);
-
shared.nstored = sem_open(SEM_NSTORED,O_CREAT|O_EXCL,FILE_MODE,0);
-
-
pthread_create(&ptid_produce,NULL,produce,NULL);
-
pthread_create(&ptid_consume,NULL,consume,NULL);
-
-
pthread_join(ptid_produce,NULL);
-
pthread_join(ptid_consume,NULL);
-
-
sem_unlink(SEM_MUTEX);
-
sem_unlink(SEM_NEMPTY);
-
sem_unlink(SEM_NSTORED);
-
-
return 0;
-
}
基于内存的信号量的单生产者单消费者
-
#include "../unipc.h"
-
-
#define NBUFF 10
-
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
-
int nitems;
-
-
struct {
-
int buff[NBUFF];
-
sem_t mutex,nempty,nstored;
-
} shared;
-
-
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(i != shared.buff[i%NBUFF]) {
-
printf("i = %d,buff[%d]=%d\n",i,i,shared.buff[i]);
-
}
-
sem_post(&shared.mutex);
-
sem_post(&shared.nempty);
-
}
-
return NULL;
-
}
-
-
int main(int argc ,char *argv[])
-
{
-
pthread_t ptid_produce,ptid_consume;
-
-
if(argc != 2 ) {
-
printf("usage produce1 <#items>\n");
-
return -1;
-
}
-
nitems = atoi(argv[1]);
-
-
sem_init(&shared.mutex,0,1);
-
sem_init(&shared.nempty,0,NBUFF);
-
sem_init(&shared.nstored,0,0);
-
-
pthread_create(&ptid_produce,NULL,produce,NULL);
-
pthread_create(&ptid_consume,NULL,consume,NULL);
-
-
pthread_join(ptid_produce,NULL);
-
pthread_join(ptid_consume,NULL);
-
-
sem_destroy(&shared.mutex);
-
sem_destroy(&shared.nempty);
-
sem_destroy(&shared.nstored);
-
return 0;
-
}
阅读(702) | 评论(0) | 转发(0) |