struct Share{
int critical;//保护区的数据
pthread_mutex_t access;//限制对 critical 访问的互斥量
};
int main()
{
struct Share * pSh = (struct Share * ) malloc(sizeof(struct Share));
pSh->critical = 0;
pthread_mutex_init(&(pSh->access),NULL);//NULL表示使用默认属性
}
pthread_mutex_wait(&mtx);
while(condition not fullfilled){
pthread_cond_wait(&cond,&mtx);
}
//在此处修改缓冲区
pthread_mutex_signal(&mtx);
//从 begin 到 end(不含end) 代表产品
//cnt 代表产品数量
//max 代表库房的容量,即最多生产多少产品
int begin = 0,end = 0, cnt = 0, max = 4;
pthread_mutex_t buf = PTHREAD_MUTEX_INITIALIZER;//用于锁住缓冲区
用 pthread_mutex_lock(&buf) 独占缓冲区;pthread_mutex_unlock(&buf); 释放缓冲区
pthread_cond_t notFull,notEmpty;//缓冲区不满;缓冲区不空
涉及到 pthread_cond_wait() 函数和 pthread_cond_signal 函数
while(1)
{
pthread_mutex_lock(&buf);
while(cnt == 0){//当缓冲区空时
pthread_cond_wait(¬Empty,&buf);
}
printf("consume %d\n",begin);
begin = (begin+1)%max;
cnt--;
pthread_mutex_unlock(&buf);
sleep(C_SLEEP);
pthread_cond_signal(¬Full);
}
while(1)
{
pthread_mutex_lock(&buf);
while(cnt == max){//当缓冲区满时
pthread_cond_wait(¬Full,&buf);
}
printf("produce %d\n",end);
end = (end+1)%max;
cnt++;
pthread_mutex_unlock(&buf);
sleep(P_SLEEP);
pthread_cond_signal(¬mpty);
}
#include "stdio.h"
#include
#include
#define N_CONSUMER 3 //消费者数量
#define N_PRODUCER 2 //生产者数量
#define C_SLEEP 1 //控制 consumer 消费的节奏
#define P_SLEEP 1 //控制 producer 生产的节奏
pthread_t ctid[N_CONSUMER];//consumer thread id
pthread_t ptid[N_PRODUCER];//producer thread id
pthread_cond_t notFull,notEmpty;//缓冲区不满;缓冲区不空
pthread_mutex_t buf = PTHREAD_MUTEX_INITIALIZER;//用于锁住缓冲区
//从 begin 到 end(不含end) 代表产品
//cnt 代表产品数量
//max 代表库房的容量,即最多生产多少产品
int begin = 0,end = 0, cnt = 0, max = 4;
void * consumer(void * pidx)//consumer thread idx
{
printf("consumer thread id %d\n",*((int *)pidx));
while(1)
{
pthread_mutex_lock(&buf);
while(cnt == 0){//当缓冲区空时
pthread_cond_wait(¬Empty,&buf);
}
printf("consume %d\n",begin);
begin = (begin+1)%max;
cnt--;
pthread_mutex_unlock(&buf);
sleep(C_SLEEP);
pthread_cond_signal(¬Full);
}
pthread_exit((void *)0);
}
void * producer(void * pidx)//producer thread idx
{
printf("producer thread id %d\n",*((int *)pidx));
while(1)
{
pthread_mutex_lock(&buf);
while(cnt == max){//当缓冲区满时
pthread_cond_wait(¬Full,&buf);
}
printf("produce %d\n",end);
end = (end+1)%max;
cnt++;
pthread_mutex_unlock(&buf);
sleep(P_SLEEP);
pthread_cond_signal(¬Empty);
}
pthread_exit((void *)0);
}
int main()
{
int i = 0;
for(i = 0; i < N_CONSUMER; i++)
{
;int * j = (int *) malloc(sizeof(int));
*j = i;
if(pthread_create(&ctid[i],NULL,consumer,j) != 0)
{
perror("create consumer failed\n");
exit(1);
}
}
for(i = 0; i < N_PRODUCER; i++)
{
int * j = (int *) malloc(sizeof(int));
*j = i;
if(pthread_create(&ptid[i],NULL,producer,j) != 0)
{
perror("create producer failed\n");
exit(1);
}
}
while(1)
{
sleep(10);
}
return 0;
}