linux C/C++交替打印A,B

知识点:

线程、互斥锁、条件变量

代码如下:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include "ThreadTest.h"


//互斥锁
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
//条件变量
pthread_cond_t condPrintA = PTHREAD_COND_INITIALIZER;
pthread_cond_t condPrintB = PTHREAD_COND_INITIALIZER;

//打印a的标志位
bool bPrintA = true;

void *ThreadPrintA(void *pParam)
{
	pthread_mutex_lock(&mtx);
	for (int i = 0; i < 10; ++i)
	{
		while(!bPrintA)
			pthread_cond_wait(&condPrintA, &mtx);
		printf("A\n");
		bPrintA = !bPrintA;
		pthread_cond_signal(&condPrintB);
	}
	pthread_mutex_unlock(&mtx);
	return NULL;
}

void *ThreadPrintB(void *pParam)
{
	pthread_mutex_lock(&mtx);
	for (int i = 0; i < 10; ++i)
	{
		while(bPrintA)
			pthread_cond_wait(&condPrintB, &mtx);
		printf("B\n");
		bPrintA = !bPrintA;
		pthread_cond_signal(&condPrintA);
	}
	pthread_mutex_unlock(&mtx);
	return NULL;
}

//线程测试Demo
void main()
{
	int ret = 0;
	pthread_t pt[2];

	ret = pthread_create(&pt[0], NULL, &ThreadPrintB, NULL);
	if (ret)
	{
		printf("pthread_create return -1,process return");
		return;
	}
	sleep(10);
	ret = pthread_create(&pt[1], NULL, &ThreadPrintA, NULL);
	if (ret)
	{
		printf("pthread_create return -1,process return");
		return;
	}
	//线程返回值
	void *pThreadRet;
	for (int i = 0; i < 2; ++i)
	{
		ret = pthread_join(pt[i],&pThreadRet);
		if (ret)
		{
			printf("pthread_join return -1,process return");
			return;
		}
	}
	
}

标志位bPrintA的作用非常明显,如果没有该标志位,那么两个线程同时启动的时候,可能出现这种情况:线程A执行到了唤醒B的条件变量,但B线程还没有获取到互斥锁,获取到锁后线程B无休止的等待被唤醒,而A又在等B唤醒,造成相互等待的死锁局面。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇龍_

若帮助到你,希望能给予鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值