//信號量---線程間通信
//“生產者消費者” 問題
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<semaphore.h>
#include<pthread.h>
#define msleep(x) usleep(x*1000)
#define PRODUCT_SPEED 3 //生產速度
#define CONSUM_SPEED 1 //消費速度
#define INIT_NUM 3 //倉庫原有產品數
#define TOTAL_NUM 10 //倉庫容量
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;
}