条件变量

条件变量是一种逻辑稍微复杂一点的同步互斥机制,条件变量必须跟互斥锁一起配合使用。
使用步骤:

1、条件变量相关API函数
在这里插入图片描述
注意:根其他的同步互斥机制一样,使用前要初始化,参数attr一般设置为NULL。当使用pthread_cond_destroy()销毁一个条件变量之后,他的值变得不确定,再使用必须重新初始化。

在这里插入图片描述

在这里插入图片描述
注意:pthread_cond_broadcast()用来唤醒全部的等待线程,pthread_cond_signal()只是换新一个等待线程。

2、例子
2.1.定义一个条件变量pthread_cond_t
2.2.初始化条件变量pthread_cond_init()
2.3.使用条件变量pthread_cond_broadcast()/pthread_cond_signal()
2.4.销毁条件变量pthread_cond_desttoy()

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/shm.h>
#include <pthread.h>
#include <semaphore.h>

int balance = 0;
pthread_mutex_t m;
pthread_cond_t v;

void *TimeCount(void *atg)
{
	static int count = 0;
	
	while(1)
	{
		sleep(1);
		printf("time:%d\n", count++);		
	}	
}

void *Routine(void *arg)
{
	
	pthread_mutex_lock(&m);					//加锁,取钱

	printf("wait before tid:%d \n", (int)arg);
	
	while(balance < 100)
		pthread_cond_wait(&v, &m);			//进入等待睡眠,同时解锁了互斥锁m,等待pthread_cond_broadcast()或者pthread_cond_signal()函数唤醒
	
	printf("wait after tid:%d, balance:%d\n", (int)arg, balance);
	balance -= 100;
	
	pthread_mutex_unlock(&m);				//解锁
	pthread_exit("routine exit");			//正常退出,并返回"routine exit"
}

int main(int argc, void *argv[])
{
	if(argc != 2)
	{
		printf("please input pthreadNum\n");
		return -1;
	}
	
	pthread_mutex_init(&m, NULL);
	pthread_cond_init(&v, NULL);
	
	pthread_t time;	
	pthread_create(&time, NULL, TimeCount, NULL);
	
	int i, timeNum = atoi(argv[1]);
	pthread_t tid;
	for(i=0; i<timeNum; i++)
	{	
		pthread_create(&tid, NULL, Routine, (void *)i );
	}
	
	sleep(3);
	pthread_mutex_lock(&m);		//加锁,在加钱即加balance
	
	sleep(3);
	balance += (timeNum - 3) * 100 ;
	
	pthread_cond_broadcast(&v);			//通知所有阻塞在条件变量里的等待线程(唤醒)
	
	pthread_mutex_unlock(&m);			//加钱后,解锁
	
	pthread_exit(NULL);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值