#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>
#define BuffSize 10
typedef struct
{
char buff[30];
}Buff;
Buff buff[BuffSize];
sem_t empty,full,visit;
int in ,out;
void * ProducerFunc(void * arg){
while (1) {
sem_wait(&empty);
sem_wait(&visit);
//opeate
sprintf(buff[in].buff,"producer");
//operate
in =(in+1)%10;
sem_post(&visit);
sem_post(&full);
printf("Hello World1!\n");
}
}
void * ConsumerFunc(void * arg){
while (1) {
sem_wait(&full);
sem_wait(&visit);
//operate
sprintf(buff[out].buff,"empty");
//operate
out = (out+1)%10;
sem_post(&visit);
sem_post(&empty);
}
}
int main(){
pthread_t proThread;
pthread_t conThread;
int ret = 0;
in=0;
out=0;
ret = sem_init(&empty,0,BuffSize);
ret = sem_init(&full,0,0);
ret = sem_init(&visit,0,1);
ret = pthread_create(&proThread,NULL,ProducerFunc,NULL);
ret = pthread_create(&conThread,NULL,ConsumerFunc,NULL);
pthread_join(&proThread,NULL);
pthread_join(&conThread,NULL);
printf("Hello World!\n");
return ret;
}
信号量-生产者消费者
最新推荐文章于 2024-07-10 05:00:00 发布
本文介绍了一个使用C/C++实现的生产者-消费者模型,通过互斥信号量(semaphores)管理缓冲区(Buff)的空闲状态和满状态,展示了线程间的协作与同步。主要关注了Producer和Consumer函数的实现,以及如何使用`sem_wait`和`sem_post`进行线程同步。
1020

被折叠的 条评论
为什么被折叠?



