您的位置:首页 > 其它

析构函数结束线程测试

2013-12-05 18:03 363 查看
  经常会碰到线程结束的难题,关系到资源的正确分配/释放,变量的引用,锁/条件变量...于是发现有一次在析构函数中通知结束线程,然后等待线程执行完毕,切换到线程运行时竟然崩溃。最初以为在析构函数中结束是有问题的,所以写了下面的代码进行测。剥离各种复杂的业务代码,经过简单测试,没有任何问题。仔细分析其实是自己释放资源的顺序不对,把线程的运行环境和变量预先销毁了,然后在等待线程执行完毕时注定出错!

  以为自己算是一个码字高手了,但还是漫不经心的犯各种小问题。

  

#include <boost/make_shared.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>

class simple_thread
{

public:
simple_thread()
{
m_run_flag = 0;
}

~simple_thread()
{
if (m_thread_grp)
{
stop();

m_thread_grp->join_all();

m_thread_grp.reset();
}
}

public:
void start()
{
m_run_flag = 1;

m_thread_grp = boost::make_shared<boost::thread_group>();

m_thread_grp->create_thread(boost::bind(&simple_thread::thread_proc, this));
}

void stop()
{
m_run_flag = 0;

m_con_scp.notify_all();
}

void thread_proc()
{
std::cout<<"thread_proc starting..."<<std::endl;

while (1)
{
Sleep(10000);

if (!m_run_flag)
{
break;
}

boost::mutex::scoped_lock lock(m_mt_scp);
m_con_scp.wait(m_mt_scp);
}

std::cout<<"thread_proc endding...."<<std::endl;
}

private:
int m_run_flag;

boost::mutex m_mt_scp;
boost::condition m_con_scp;
boost::shared_ptr<boost::thread_group> m_thread_grp;
};

int _tmain(int argc, _TCHAR* argv[])
{
if (1)
{
boost::shared_ptr<simple_thread> test = boost::make_shared<simple_thread>();
test->start();

std::cout<<"object destroying...."<<std::endl;
}

Sleep(INFINITE);

return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: