//5.生产者消费者问题 #include <pthread.h> #include <semaphore.h> #include <unistd.h> #include <stdio.h> #define MAX 50 #define BUFSIZE 10 //仓库的大小 int buf[BUFSIZE]={0}; int in=0; int out=0; sem_t full,empty; void* producer(void* arg) { int i; for (i = 1;i<=MAX;++i) { /*produce*/ sem_wait(&full); buf[in++]=i; in%=BUFSIZE; printf("生产了第%d个产品\n" ,i); sem_post(&empty); } pthread_exit((void*)"thread1 exit\n"); } void* comsumer(void* arg) { int i,data_c; for (i = 1;i<= MAX; ++i) { /*comsumer*/ sem_wait(&empty); data_c=buf[out++]; out%=BUFSIZE; printf("消费了%d个产品\n" ,data_c); sem_post(&full); } pthread_exit((void*)"thread2 exit\n"); } int main(void) { void *tret; sem_init(&full,0,10); //信号量的初始值为10和仓库的大小保持一致 sem_init(&empty,0,0); pthread_t tid_producer,tid_comsumer; pthread_create(&tid_producer,NULL,producer,NULL); pthread_create(&tid_comsumer,NULL,comsumer,NULL); pthread_join(tid_producer,&tret); printf("%s\n",(char*)tret); pthread_join(tid_comsumer,&tret); printf("%s\n",(char*)tret); sem_destroy(&full); sem_destroy(&empty); return 0; }此程序一定要注意信号量的个数一定要和仓库的存储空间大小数值上要一样大,此程序两个数都为10
时间: 2024-10-06 19:46:12