//訊號量---線程間通訊//“生產者消費者” 問題#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<semaphore.h>#include<pthread.h>#definemsleep(x)usleep(x*1000)#define PRODUCT_SPEED3//生產速度#define CONSUM_SPEED1//消費速度#define INIT_NUM3//倉庫原有產品數#defineTOTAL_NUM10//倉庫容量sem_t p_sem, c_sem, sh_sem;int num=INIT_NUM;void product(void)//生產產品{sleep(PRODUCT_SPEED);}int add_to_lib()//添加產品到倉庫{num++;//倉庫中的產品增加一個msleep(500);return num;}void consum()//消費{sleep(CONSUM_SPEED);}int sub_from_lib()//從倉庫中取出產品{num--; //倉庫中的產品數量減一msleep(500);return num;}void *productor(void *arg)//生產者線程{while(1){sem_wait(&p_sem);//生產訊號量減一product();// 生產延時sem_wait(&sh_sem);//這個訊號量是用來互斥的printf("push into! tatol_num=%d\n",add_to_lib());sem_post(&sh_sem);sem_post(&c_sem); //消費訊號量加一}}void *consumer(void *arg)//消費者線程{while(1){sem_wait(&c_sem); //消費者訊號量減一sem_wait(&sh_sem);printf("pop out! tatol_num=%d\n",sub_from_lib());sem_post(&sh_sem);sem_post(&p_sem);//生產者訊號量加一consum();//消費延時}}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;}