有四个进程P1,P2,P3,P4共享一个缓冲区,进程P1向缓冲区中存入消息,进程P2,P3,P4从缓冲区中取消息,要求发送者必须等3个进程都取过本条消息后才能发送下一个条消息。缓冲区内每次只能容纳一个消息,用PV操作描述四个进程存取消息的情况。
分析:同步+互斥,临界区里放1个资源
源码:
sem_t s1,s2,s3;
sem_t b1,b2,b3;
sem_t mutex;
void myThread1(void);
void myThread2(void);
void myThread3(void);
void myThread4(void);
int main()
{
pthread_t id[4];
int i;
sem_init(&mutex, 0, 1);
sem_init(&s1, 0, 0);
sem_init(&s2, 0, 0);
sem_init(&s3, 0, 0);
sem_init(&b1, 0, 1);
sem_init(&b2, 0, 1);
sem_init(&b3, 0, 1);
pthread_create(&id[0], NULL, (void*)myThread1, NULL); //0 producer
pthread_create(&id[1], NULL, (void*)myThread2, NULL); //1 consumer
pthread_create(&id[2], NULL, (void*)myThread3, NULL); //2 consumer
pthread_create(&id[3], NULL, (void*)myThread4, NULL); //3 consumer
for(i=0;i<4;i++)
{
pthread_join(id[i], NULL);
}
sem_destroy(&s1);
sem_destroy(&s2);
sem_destroy(&s3);
sem_destroy(&b1);
sem_destroy(&b2);
sem_destroy(&b3);
return 0;
}
void myThread1(void)
{
while(1)
{
sem_wait(&b1);
sem_wait(&b2);
sem_wait(&b3);
sem_wait(&mutex);
printf("p1 :produce\n");
sem_post(&mutex);
sleep(1);
sem_post(&s1);
sem_post(&s2);
sem_post(&s3);
}
}
void myThread2(void)
{
while(1)
{
sem_wait(&s1);
sem_wait(&mutex);
printf("p2 :consume\n");
sem_post(&mutex);
sleep(1);
sem_post(&b1);
}
}
void myThread3(void)
{
while(1)
{
sem_wait(&s2);
sem_wait(&mutex);
printf("p3 :consume\n");
sem_post(&mutex);
sleep(1);
sem_post(&b2);
}
}
void myThread4(void)
{
while(1)
{
sem_wait(&s3);
sem_wait(&mutex);
printf("p4 :consume\n");
sem_post(&mutex);
sleep(1);
sem_post(&b3);
}
}