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

知识点:

线程、互斥锁、条件变量

代码如下:

#include 
#include 
#include 
#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唤醒,造成相互等待的死锁局面。

你可能感兴趣的:(linux,C/C++)