LV6 day9 条件变量的使用及注意事项

条件变量

应用场景:生产者消费者问题,是线程同步的一种手段。
必要性:为了实现等待某个资源,让线程休眠。提高运行效率
int pthread_cond_wait(pthread_cond_t *restrict cond
pthread_mutex_t *restrict mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex,
const struct timespec *restrict abstime);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);

使用步骤:

初始化:
静态初始化
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //初始化条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //初始化互斥量
或使用动态初始化
pthread_cond_init(&cond);
生产资源线程:
pthread_mutex_lock(&mutex);
开始产生资源
pthread_cond_sigal(&cond); //通知一个消费线程
或者
pthread_cond_broadcast(&cond); //广播通知多个消费线程
pthread_mutex_unlock(&mutex);

消费者线程:

pthread_mutex_lock(&mutex);
while (如果没有资源){ //防止惊群效应
pthread_cond_wait(&cond, &mutex);
}
有资源了,消费资源
pthread_mutex_unlock(&mutex);
注意:
1 pthread_cond_wait(&cond, &mutex),在没有资源等待是是先unlock 休眠,等资源到了,再lock
所以pthread_cond_wait he pthread_mutex_lock 必须配对使用。
2 如果pthread_cond_signal或者pthread_cond_broadcast 早于 pthread_cond_wait ,则有可能会丢失信号。
3 pthead_cond_broadcast 信号会被多个线程收到,这叫线程的惊群效应。所以需要加上判断条件while循环。

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include<stdlib.h>
pthread_cond_t hastaxi=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
struct taxi{
	struct 	taxi *next;
	int num;
};
struct tax *Head=NULL;



void *taxiarv(void *arg)
{
	printf("taxi arrived thread\n");
	pthread_detach(pthread_self());
	struct taxi *tx;
	int i=1;
	while(1){
		tx=malloc(sizeof(struct taxi));
		tx->num=i++;
		printf("taxi %d coming\n",tx->num);
		
		pthread_mutex_lock(&lock);
	
		tx->next=Head;
		Head=tx;
	
		pthread_cond_signal(&hastaxi);
		
		pthread_mutex_unlock(&lock);
		sleep(1);
	}

	pthread_exit(0);


}
void *taketaxi(void *arg)
{
	printf("take taxi arrived thread\n");
	pthread_detach(pthread_self());
	struct taxi *tx;
	while(1){
		pthread_mutex_lock(&lock);
		while(Head==NULL)
		{
		pthread_cond_wait(&hastaxi,&lock);		
		}
		tx=Head;
		Head=tx->next;

		printf("take taxi %d\n",tx->num);
		free(tx);
		pthread_mutex_unlock(&lock);

	}

	pthread_exit(0);
}



int main(int argc, char *argv[])
{
	pthread_t tid1,tid2;
	pthread_create(&tid1,NULL,taxiarv,NULL);
	pthread_create(&tid2,NULL,taketaxi,NULL);
	while(1){
		sleep(1);
	}
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值