std::thread库的condition_variable进行线程唤醒

转载请注明出处:http://my.csdn.NET/ye_shen_wei_mian

很久之前写了的测试程序,主要实现的功能是:

线程run1:

线程run1在运行过程中通过检测状态量mbAcceptKeyFrames_是否为true来判定线程run2是否已经处理其事务完毕(或者说是空闲状态,处于挂起状态)。

若检测到run2处于空闲状态,则设置状态量insertNewKeyframe为true,并通过条件变量来唤醒run2。若检测到run2处于繁忙状态(run2还没处理完成自己的事务),则不做任何操作。

之后随即run1继续处理自己的事务。


线程run2:

run2检测到insertNewKeyframe这个状态量为真时,则拿到锁锁住mutexSychron_,并设置mbAcceptKeyFrames_为false,并开始处理run2的事务,处理完毕了再释放掉锁mutexSychron_,随后把状态量mbAcceptKeyFrames_设置为true,把insertNewKeyframe设置为false。


上述功能用通俗的话来讲就是:run1通过run2挂的牌子(mbAcceptKeyFrames_)看看run2忙不忙,不忙的话(mbAcceptKeyFrames_为true)run1就可以给run2东西去忙(通过条件变量去唤醒run2,insertNewKeyframe = true),忙run1就先让run2继续忙你的我就不打扰你了。run2如果没东西忙,run2就说哦我现在不忙(令mbAcceptKeyFrames_为true,我现在没啥事干正喝着咖啡等着run1你给东西给我忙(挂起)。如果run2在忙的话,也会挂个牌子(mbAcceptKeyFrames_为false)让run1看到我现在很忙,别给我东西忙了。等run2忙完了,也会挂个牌子mbAcceptKeyFrames_为true,insertNewKeyframe = false)说我忙完了你给我的东西了,可以接新活了,然后去喝咖啡歇着(挂起),等着run1再给他东西干。

事不宜迟吧,先上代码:

#include
#include
#include
#include 

using namespace std;

bool mbAcceptKeyFrames_;
std::mutex mMutexAccept_;
std::mutex mutexSychron_;

bool insertNewKeyframe;

std::condition_variable cv; // 全局条件变量


void SetAcceptKeyFrames(bool flag)
{
	std::unique_lock lock(mMutexAccept_);
	std::cout << "Thread run2 set accepted keyframe = "<< flag < lock(mMutexAccept_);
	std::cout << "Thread run1 detect accepted keyframe = " << mbAcceptKeyFrames_ << std::endl;
	return mbAcceptKeyFrames_;
}


void run1(unsigned int timstamp)
{
	//insertNewKeyframe = false;
	for (int i = 0; i < 10; i++)
	{
		std::cout << "Thread run1 doing other operations...blablabla" << endl;
	}
	

	bool newKeyframeOrNot = AcceptKeyFrames();
	
	//std::unique_lock lock(mutexSychron_);
	if (newKeyframeOrNot)
	{
		std::unique_lock lock(mutexSychron_);
		std::cout << "Thread run1 wakes up run2" << endl;
		insertNewKeyframe = true;
		cv.notify_one();
		lock.unlock();
	}
	
	for (int i = 0; i < 10; i++)
	{
		std::cout << "Thread run1 doing other operations...blingblingbling" << endl;
	}
}

void run2()
{
	while (true)
	{
		SetAcceptKeyFrames(true);
		insertNewKeyframe = false;

		std::unique_lock lock(mutexSychron_);
		while (!insertNewKeyframe)
			cv.wait(lock);

		SetAcceptKeyFrames(false);
		//lock.unlock();

		//线程被唤醒
		std::cout << "Thread run2 now wakes up " << std::endl;
		
		

		for (int i = 0; i < 100; i++)
		{
			std::cout << "Thread run2 is doing its own work.. " << std::endl;
		}
		std::cout << "Thread run2's work done , go back to sleep until waked" << std::endl;

		lock.unlock();
	}
}


int main()
{
	thread Thread2(&run2);

	for (unsigned int t = 0; t < 10000; t++)
	{
		run1(t);
	}
	return 0;
}



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