Semaphore---Inter-thread communication/"producer Consumer" issue #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include & lt;semaphore.h> #include <pthread.h> #define MSLEEP (x) usleep (x*1000) #define Product_speed 3 Production speed #define CONSUM_SPEED 1//consumption speed #define INIT_NUM 3//Warehouse
Number of original products #define TOTAL_NUM 10//Warehouse capacity sem_t P_sem, C_sem, Sh_sem;
int num=init_num;
void product (void)//production product {sleep (product_speed);
int add_to_lib ()//Add product to warehouse {num++;//Warehouse add a msleep (500);
return num;
} void Consum ()//consumption {sleep (consum_speed);
int sub_from_lib ()//Remove product from warehouse {num--;//The quantity of products in the warehouse is reduced by one msleep (500);
return num; } void *productor (void *arg) Producer Thread {while (1) {sem_wait (&P_SEM);//production signal quantity minus one product ();//Production delay Sem_wait (&sh_sem);//This semaphore is used to mutually exclusive printf ("Push into!
Tatol_num=%d\n ", Add_to_lib ());
Sem_post (&sh_sem); Sem_post (&c_sem);
Consumption semaphore plus One} void *consumer (void *arg)//consumer thread {while (1) { Sem_wait (&c_sem);
The consumer signal quantity is reduced by one sem_wait (&sh_sem); printf ("Pop out!
Tatol_num=%d\n ", Sub_from_lib ());
Sem_post (&sh_sem);
Sem_post (&p_sem)/producer Semaphore plus one consum ()//Consumption delay}}
int main () {pthread_t tid1,tid2;
Sem_init (&p_sem,0,total_num-init_num);
Sem_init (&c_sem,0,init_num);
Sem_init (&sh_sem,0,1);
Pthread_create (&tid1,null,productor,null); Pthread_create(&tid2,null,consumer,null);
Pthread_join (Tid1,null);
Pthread_join (Tid2,null);
return 0; }