尽量不要在生产环境代码中使用boost::this_thread::sleep

/********************************************************/
/*Author:fyu0609@csdn.net                               */
/*如何使用 boost::thread,                               */
/*boost::this_thread::sleep、                           */
/*boost::mutex、 boost::condition进行多线程编程         */
/********************************************************/

#include <iostream>
#include "boost/thread.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/bind.hpp"
#include "boost/thread/condition.hpp"

using namespace std;

class TestMultiThread
{
public:
	TestMultiThread():bStop(false)
	{
		pThread = new boost::thread(boost::bind(&TestMultiThread::func, this));
	}
	~TestMultiThread()
	{
		bStop = true;
		pThread->join();
		delete pThread;
		pThread = NULL;
	}
private:
	void func()
	{
		while(!bStop)
		{	
			boost::this_thread::sleep(boost::posix_time::seconds(5));
			cout<<"Another 5 seconds"<<endl;
		}
	}
private:
	//禁止拷贝,赋值
	TestMultiThread(const TestMultiThread&);
	TestMultiThread& operator = (const TestMultiThread&);
private:
	bool bStop;
	boost::thread* pThread;
};


void main()
{
	char cmd;
	TestMultiThread t1;
	while(1)
	{
		cout<<"Please type any key to exit."<<endl;
		cin>>cmd;
		cout<<"The Programe is end now."<<endl;
		return;
	}

}

运行程序,输入任意字符,回车;

程序输出“The Progame is end now.”,但是却不会立即退出。

直到程序输出“Another 5 seconds”后,才会退出。

1.函数在return后不会立即返回,而是先退栈,再返回。

上面的程序,return之后,主线程实际转入TestMultiThread的析构函数中执行。必须等到func子线程退出,主线程才能退出。

2.在生产环境代码中使用boost::this_thread::sleep或者其他使进程/线程,休眠/挂起的函数时,一定要谨慎。

  只有确认当前线程不存在与其他任何线程同步的情形下,才能使用这些函数。

一旦涉及同步,请使用boost::mutex、 boost::condition等其他类似的同步原语。

上面的程序正确实现方法如下:

class TestMultiThread
{
public:
	typedef boost::mutex::scoped_lock LockType;
public:
	TestMultiThread()
	{
		pThread = new boost::thread(boost::bind(&TestMultiThread::func, this));
	}
	~TestMultiThread()
	{
		{
			LockType lock(stopMutex);
			stopCondition.notify_all();
		}
		
		pThread->join();
		delete pThread;
		pThread = NULL;
	}
private:
	void func()
	{
		bool wakeByCondition = false;
		while(1)
		{	
			{
				LockType lock(stopMutex);
				wakeByCondition = stopCondition.timed_wait(lock, boost::posix_time::seconds(5));
			}
			if(wakeByCondition)
			{
				cout<<"Receive a notify"<<endl;
				break;
			}
			else
			{
				cout<<"Another 5 seconds"<<endl;
			}
			
		}
	}
private:
	//禁止拷贝,赋值
	TestMultiThread(const TestMultiThread&);
	TestMultiThread& operator = (const TestMultiThread&);
private:
	boost::thread* pThread;
	boost::mutex   stopMutex;
	boost::condition stopCondition;
};



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值