linux条件锁pthread_cond_t使用示例

等待线程 [喝小酒的网摘]http://blog.hehehehehe.cn/a/17163.htm
1。使用pthread_cond_wait前要先加锁
2。pthread_cond_wait内部会解锁,然后等待条件变量被其它线程激活(pthread_cond_signal发送信号)
3。pthread_cond_wait被激活后会再自动加锁

激活线程:
1。加锁(和等待线程用同一个锁)
2。pthread_cond_signal发送信号
3。解锁
激活线程的上面三个操作在运行时间上都在等待线程的pthread_cond_wait函数内部。

程序示例:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>

pthread_mutex_t lock;
pthread_cond_t  cond;

int sum;

void* dec(void *argv)
{
    pthread_mutex_lock(&lock);
    while(sum==0)
    {
        printf("dec sum=0 ");
        pthread_cond_wait(&cond,&lock);    
    }    
    sum--;
    pthread_mutex_unlock(&lock);
    printf("dec sum=%d ",sum);
    pthread_exit(NULL);
    return 0;
}

void* add(void *argv)
{
    pthread_mutex_lock(&lock);
    if(sum==0)
    {
        printf("add sum =0 ");
        pthread_cond_signal(&cond);    
    }    
    sum++;
    
    pthread_mutex_unlock(&lock);
    sleep(1);
    sum++;
    printf("add sum=%d ",sum);
    pthread_exit(NULL);
    return 0;    
}

int main(int argc,char** argv)
{
    pthread_t ptid1,ptid2;
    sum = 0;
    pthread_mutex_init(&lock,NULL);
    pthread_cond_init(&cond,NULL);
    
    pthread_create(&ptid1,NULL,dec,NULL);
    pthread_create(&ptid2,NULL,add,NULL);
    
    
    int counter = 0;  
  while(counter != 10){  
      printf("counter: %d ", counter);  
    sleep(1);  
    counter++;  
  }  
    
    return 0;    
}


运行结果:

dec sum=0
counter: 0
add sum =0
dec sum=0
add sum=1
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
counter: 6
counter: 7
counter: 8
counter: 9

[喝小酒的网摘]http://blog.hehehehehe.cn/a/17163.htm
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值