#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-04-15 18:29:55 发布