就像值日一样, 设定好值日表, 你一三五, 我二四六
下面的代码使用轮转法实现生产者消费者不断地轮转生产消费
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <typeinfo.h>
#include <sys/time.h>
#include <unistd.h>
#define MAX_NUM 10
int count = 1;
int turn = 0;
void* consume(void* arg)
{
while(true){
while(turn!=0 || count==0){}
printf("剩余:%d, 开始消费\n", count);
sleep(1);
count --;
printf("剩余:%d, 结束消费\n", count);
turn = 1;
}
return 0;
}
void* produce(void* arg)
{
while(true){
while(turn!=1 || count==MAX_NUM){}
printf(" 剩余:%d, 开始生产\n", count);
sleep(1);
count ++;
printf(" 剩余:%d, 结束生产\n", count);
turn = 0;
}
return 0;
}
void* run(void* arg)
{
int i;
for(i=0; i<10; i++){
printf("Hello world!\n");
}
i=0;
while(i<MAX_NUM){
printf("Hello, %d\n", i);
i ++;
}
printf("max_num: %d", MAX_NUM);
}
int main(void)
{
pthread_t t1;
pthread_t t2;
pthread_create(&t1, NULL, consume, NULL);
pthread_create(&t1, NULL, produce, NULL);
pthread_join(t1, NULL);
return 0;
}
/*
当count=0且turn=0时候, 开始就产生一个死锁
*/
问题:
- 当turn初始值为0, count初始值为0时候, 开始程序就产生死锁.