【Boost】boost库中thread多线程详解7——wait与timed_wait简单例子

namespace
{
	void wait(int seconds)
	{
		boost::this_thread::sleep(boost::posix_time::seconds(seconds));
	}

	boost::mutex mu;
	boost::condition_variable_any cond;

	void test_wait()
	{
		while(true)
		{
			boost::mutex::scoped_lock lock(mu);
			cond.wait(mu);
			PRINT_DEBUG(boost::this_thread::get_id() << "收到notify!");
		}
	}

	void test_timed_wait() {
		while(true)
		{
			boost::mutex::scoped_lock lock(mu);
			if (cond.timed_wait(lock, boost::get_system_time() + boost::posix_time::seconds(3))) 
			{
				PRINT_DEBUG("收到notify!");
			} else {
				PRINT_DEBUG("超时, 没有收到Notify!");
			}
		}
	}
}

void test_thread_wait()
{
	boost::thread t1(test_wait);
	boost::thread t2(test_wait);
	boost::thread t3(test_wait);
	boost::thread t4(test_wait);
	while (true)
	{
		wait(1);
		cond.notify_one();
	}
}

void test_thread_timed_wait()
{
	boost::thread t1(test_timed_wait);
	while (true)
	{
		system("pause");
		cond.notify_one();
	}
}

你可能感兴趣的:(【Boost】boost库中thread多线程详解7——wait与timed_wait简单例子)