利用pthread_mutex_t和thread_cond_t实现多线程交替打印

利用pthread_mutex_t和thread_cond_t实现多线程交替打印

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

#define COUNT 100

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t  cond2 = PTHREAD_COND_INITIALIZER;
static int loop = 1;

void *fun1(void* arg)
{
	while (loop < COUNT) {
		pthread_mutex_lock(&mutex);
		if (loop%2 != 0) {
			printf("1\n");
			loop++;
			pthread_cond_signal(&cond2);
		} else {
			pthread_cond_wait(&cond1, &mutex);
		}
		pthread_mutex_unlock(&mutex);
	}
}

void *fun2(void* arg)
{
	while (loop < COUNT) {
		pthread_mutex_lock(&mutex);
		if (loop % 2 == 0) {
			printf("2\n");
			loop++;
			pthread_cond_signal(&cond1);
		} else {
			pthread_cond_wait(&cond2, &mutex);
		}
		pthread_mutex_unlock(&mutex);
	}
}

int main(void)
{
	pthread_t id1;
	pthread_t id2;
	printf("main thread enter\n");
	
	pthread_create(&id1, NULL, fun1, NULL);
	pthread_create(&id2, NULL, fun2, NULL);
	
	pthread_join(id1, NULL);
	pthread_join(id2, NULL);

	printf("man thread exit\n");
}
  • pthread_cond_wait前要先加锁
  • pthread_cond_wait内部会解锁,然后等待条件变量被其它线程激活
  • pthread_cond_wait被激活后会再自动加锁
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值