//5. Producer Consumer issues#include <pthread.h>#include<semaphore.h>#include<unistd.h>#include<stdio.h>#defineMAX 50#defineBUFSIZETen //Size of warehouseintbuf[bufsize]={0}; int inch=0; int out=0; Sem_t Full,empty; void* Producer (void*Arg) { inti; for(i =1; i<=max;++i) {/*Produce*/sem_wait (&Full ); buf[inch++]=i; inch%=BUFSIZE; printf ("production of%d products \ n", i); Sem_post (&empty); } pthread_exit ((void*)"Thread1 exit\n"); } void* Comsumer (void*Arg) { intI,data_c; for(i =1; i<= MAX; ++i) {/*Comsumer*/sem_wait (&empty); Data_c=buf[ out++]; out%=BUFSIZE; printf ("%d products were consumed \ n", Data_c); Sem_post (&Full ); } pthread_exit ((void*)"thread2 exit\n"); } intMainvoid) { void*Tret; Sem_init (&full,0,Ten); the initial value of the semaphore is 10 and the warehouse size remains consistent 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;}
This program must pay attention to the number of semaphores must be the same size as the storage space of the warehouse, the program two number is ten
Producer consumer issues (thread-based and nameless semaphores)