首先分析一下outMsgProc()这个函数。  它先给互斥量myMutex加锁,然后在判断myList是否为空。myList为空时,需要释放锁,此时锁的添加和释放需要无意义的消耗资源。

bool outMsgProc(int &num)
{	
	std::unique_lock<std::mutex> guard(myMutex);
	if (!myList.empty())
	{
		num = myList.front();
		myList.pop_front();
		return true;
	}	
	return false;
}

      更好的方法是采用双重检查。先判断myList是否为空,myList为空时函数直接返回。当它不为空时,才对互斥量加锁。当然,加锁后需要重新判断myList是否为空。双重检查避免了无意义的添加和释放锁,提高了程序效率。

bool outMsgProc(int &num)
{
	if (!myList.empty())  //双重检查,提高效率
	{
		std::unique_lock<std::mutex> guard(myMutex);
		if (!myList.empty())
		{
			num = myList.front();
			myList.pop_front();
			return true;
		}
	}		
	return false;
}

      上述代码是否还有改进的空间?思考一下,当成千上万次的调用函数outMstProc(),而myList始终为空时,if(!myList.empty())语句被会不断的执行。为了避免if判断过多无意义的执行,可以在myList为空时,让程序休眠一定的时间。

bool outMsgProc(int &num)
{
	if (!myList.empty())  //双重检查,提高效率
	{
		std::unique_lock<std::mutex> guard(myMutex);
		if (!myList.empty())
		{
			num = myList.front();
			myList.pop_front();
			return true;
		}
	}
	else
	{
		std::chrono::milliseconds time(200);   //暂停200毫秒
		std::this_thread::sleep_for(time);
	}
	return false;
}

 

 


版权声明:本文为liyazhen2011原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/liyazhen2011/article/details/88594623