进程同步--临界区保护(1)_轮转法

就像值日一样, 设定好值日表, 你一三五, 我二四六

下面的代码使用轮转法实现生产者消费者不断地轮转生产消费

#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时候, 开始就产生一个死锁 
*/

问题:

  1. 当turn初始值为0, count初始值为0时候, 开始程序就产生死锁.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值