条件变量与锁趣味性测试

std::condition_variable cvWaitThread;
int a = 100;
std::mutex mt;
void tt()
{
	std::lock_guard<std::mutex> lc(mt);
	for (int i = 1; i <= 6; i++)
	{
		Sleep(1000);
		printf("tt-%d\n",i);
	}
	
}



void tt3()
{
	for (int i = 1; i <= 15; i++)
	{
		Sleep(1000);
		printf("tt3-%d\n", i);
	}

	a = 10;
	cvWaitThread.notify_all();
}
int main()
{

	thread t(tt);
	t.detach();
	Sleep(2000);



	thread t2(tt3);
	t2.detach();

	{
		cout << "尝试锁住\n";
		std::unique_lock<mutex>lc(mt);
		cout << "已经锁住,等待条件\n";
		cvWaitThread.wait(lc, []() {return a == 10; });
		cout << "hello world 1\n";
	}
	{
		cout << "尝试锁住\n";
		std::unique_lock<mutex>lc(mt);
		cout << "已经锁住,等待条件\n";
		cvWaitThread.wait(lc, []() {return a == 10; });
		cout << "hello world 2\n";
	}
	
	{
		cout << "尝试锁住\n";
		std::unique_lock<mutex>lc(mt);
		cout << "已经锁住,等待条件\n";
		cvWaitThread.wait(lc, []() {return a == 10; });
		cout << "hello world 3\n";
	}
	


	system("pause");
	return 0;
}

结果:
条件变量与锁趣味性测试_第1张图片
结论:如果当前锁已经被其它线程锁住,那么锁的时候会等待,直到其它线程释放锁。

你可能感兴趣的:(C/C++基础,c++)