进程间的PV操作,一个生产者一个消费者一个缓冲区,通过对信号量的操作完成线程间的同步。
程序:
#include <semaphore.h>
#include <pthread.h>#include <stdio.h>
#include <stdlib.h>
sem_t full;
sem_t empty;
char buff[100];
int num = 0;
void producer()//生产者
{
while(1)
{
sem_wait(&empty);//P操作
num++;
printf("生产:");
scanf("%s",buff);
if(strncmp(buff,"quit",4) == 0)//判断是否为退出
{
printf("quit!\n");
exit(0);
}
sem_post(&full);
}
}
void consumer()//消费者
{
while(1)
{
sem_wait(&full);
num++;
printf("消费:%s\n",buff);
sem_post(&empty);
}
}
int main()
{
pthread_t p1,p2;
sem_init(&full,0,0);
sem_init(&empty,0,1);
if(pthread_create(&p1,NULL,(void *)producer,NULL) < 0)//创建进程
{
printf("pthread create error\n");
exit(1);
}
if(pthread_create(&p2,NULL,(void *)consumer,NULL) < 0)
{
printf("pthread create error\n");
exit(1);
}
sem_destroy(&full);//消除信号量
sem_destroy(&empty);
pthread_join(p1,NULL);//等待进程结束
pthread_join(p2,NULL);
return 0;
}
一个在努力中的未来程序员,如果有更好的想法,欢迎评论。