Linux--多线程条件变量使用

条件变量是为了控制多线程的互斥问题,同时个人觉得有点多线程协作同步的意思在里面。消费者线程等待取生产者线程提供的资源,生产者线程生产产品后就通知唤醒消费者线程进行资源获取。一般条件变量与互斥量共用。

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

typedef struct product_node
{
	char name[32];
	int number;
	struct product_node *next;
}product;

product *product_container = NULL;  
int counter = 0;
pthread_cond_t product_cond;
pthread_mutex_t product_mutex;

void * producer(void *arg)
{
	while(1)
	{
		time_t tt = time(NULL);
		product *tmp = (product *)malloc(sizeof(product));
		if (tmp == NULL)
		{
			printf("malloc error\n");
			pthread_exit((void *)-1);
		}
		
		ctime_r(&tt, tmp->name);
		pthread_mutex_lock(&product_mutex);
		tmp->number = counter++;
		tmp->next = product_container;
		product_container = tmp;
		pthread_mutex_unlock(&product_mutex);
		pthread_cond_broadcast(&product_cond);
		
		//如果不加sleep, 那么生产者线程会在消费者线程sleep途中一直能得到锁
		//导致counter++无数次
		sleep(1);
	}
}

void * consumer(void *arg)
{
	product *one_product;
	while(1)
	{
		pthread_mutex_lock(&product_mutex);
		while(product_container == NULL)
		{
			//阻塞线程同时释放互斥锁,这就是为什么需要传递一个互斥锁的原因,如果第二个参数的互斥锁和上面lock
			//时候的锁不一致就会导致问题。释放互斥锁的原因是让生产者线程能够及时地获取锁放入产品。当条件变量
			//得到满足同时能够离开循环, 刚才释放的互斥锁又会重新加上
			pthread_cond_wait(&product_cond, &product_mutex);
		}
		
		one_product = product_container;
		product_container = product_container->next;
		pthread_mutex_unlock(&product_mutex);
		
		one_product->name[strlen(one_product->name) - 1] = 0;
		printf("name[%s] get number[%d] product\n", one_product->name, one_product->number);
		free(one_product);
		
		sleep(1);
	}
}

int main()
{
	pthread_t worker, saler;
	
	pthread_cond_init(&product_cond, NULL);
	pthread_mutex_init(&product_mutex, NULL);
	
	pthread_create(&worker, NULL, producer, NULL);
	pthread_create(&saler, NULL, consumer, NULL);
	
	pthread_join(worker, NULL);
	pthread_join(saler, NULL);
	
	pthread_cond_destroy(&product_cond);
	pthread_mutex_destroy(&product_mutex);
	
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值