进程访问共享空间关于信号量的使用
描述: 我们公司现在召开一场运动会。运动会参与人数1000000人 现在因为打印机坏了
运动员后面的号码牌(从0到999999)需要手写。此时我司临时招聘了5个工人来帮我们写
因为公司太穷了 笔只有一只。谁拿到了笔谁就写。最好时每个人写了多少数字记录以下
到时候好计算工资,另外我们考虑到可能有人会写错 所以我们就派了一个经理去检查是否正确。
#include <pthread.h>
#include <stdio.h>
//工人的数量
#define MAXTHREADS 5
//号码牌的个数
#define MAXNUM 1000000
//线程互斥锁 静态初始化
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//号码牌
int buf[MAXNUM];
//号码牌的编号 --》下标
int num = 0;
//号码牌的值val应该要与号码牌的编号num相等 意思就是编号为0的号码牌上面要写0
//即buf[0] = 0 buf[1]=1 ... 编号为num的号码牌上要写val 。buf[num] = val;
int val = 0;
//信号量
pthread_cond_t c;
//经理的遍历
int i=0;
//工人:生产者
void * produce(void * arg)
{
while(1)
{
//上锁
pthread_mutex_lock(&mutex);
if(num >= 1000000)
{
pthread_mutex_unlock(&mutex);
return NULL; //号码牌写完了 任务完成 解锁出去
}
buf[num] = val;
num++;
val++;
*((int *)arg)+= 1;
//解锁
pthread_mutex_unlock(&mutex);
}
}
//经理:消费者
void * consume(void * arg)
{
if(i > num)//检查的量超过写的
{
pthread_cond_wait(&c,&mutex);
}
if(buf[i] != i && i<num)//把不满足条件的打印出来
{
printf("buf[%d] = %d\n",i,buf[i]);
}
return NULL;
}
int main()
{
pthread_cond_init(&c,NULL);
//用来保存5个线程的id
pthread_t tids[MAXTHREADS];
//用来计算每个工人写号码牌的个数
int count[MAXTHREADS]={0};
//招5个工人去写号码牌
int i;
for(i=0;i<MAXTHREADS;i++)
{
pthread_create(&tids[i],NULL,produce, (void *)(&count[i]) );
}
//派一个经理去检查数据是否正确
pthread_t tid;
pthread_create(&tid,NULL,consume,NULL);
//判断是否还有未检查的
while(1)
{
i++;
if(i<num && i<MAXNUM)
{
pthread_cond_signal(&c);
}
else if(i == MAXNUM)
{
break;
}
}
//等待线程结束并释放资源
//等待生产者
for(i=0;i<MAXTHREADS;i++)
{
pthread_join(tids[i],NULL);
printf("count[%d] = %d\n",i,count[i]);
}
//等待消费者
pthread_join(tid,NULL);
pthread_cond_destroy(&c);
}