/********************************************************/
/*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;
};