Linux_线程的条件变量

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

#define PTHREAD_NUM 10

static int global = 0;
static pthread_mutex_t m;
static pthread_cond_t v;

void *count_times(void *args)
{
	int i = 1;
	while(1)
	{
		sleep(1);
		fprintf(stderr, "second: %d\n", i++);
	}
	return (void *)0;  //等价于NULL
}

void *tfn(void *args)
{
	pthread_mutex_lock(&m);

	while(global != 100)
	{
		//进入该函数,做两件事情:1.解锁,2.阻塞
		pthread_cond_wait(&v, &m);  //在此形成阻塞队列
		//收到pthread_cond_broadcast, 从该函数返回做一件事:加锁
	}
	//临界区(进程中访问临界资源的那段代码)
	fprintf(stdout, "t%d:global = %d\n", (int)args, global);
	pthread_mutex_unlock(&m);
	return (void *)0;
}

int main(void)
{
	int i;
	pthread_t tidd;
	pthread_t tid[PTHREAD_NUM];

	pthread_mutex_init(&m, NULL);
	pthread_cond_init(&v, NULL);

	pthread_create(&tidd, NULL, count_times, NULL);

	for(i=0; i<PTHREAD_NUM; i++)
	{
		if(pthread_create(&tid[i], NULL, (void *)tfn, (void *)i) != 0)
		{
			perror("pthread_create failed");
		}
	}

	sleep(1);
	pthread_mutex_lock(&m);
	global = 100;
	pthread_cond_broadcast(&v); //向所有等待条件的线程发送信号
	sleep(3);
	pthread_mutex_unlock(&m);

	for(i=0; i < PTHREAD_NUM; i++)
	{
		pthread_join(tid[i], NULL);
	}

	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值