析构函数结束线程测试
2013-12-05 18:03
363 查看
经常会碰到线程结束的难题,关系到资源的正确分配/释放,变量的引用,锁/条件变量...于是发现有一次在析构函数中通知结束线程,然后等待线程执行完毕,切换到线程运行时竟然崩溃。最初以为在析构函数中结束是有问题的,所以写了下面的代码进行测。剥离各种复杂的业务代码,经过简单测试,没有任何问题。仔细分析其实是自己释放资源的顺序不对,把线程的运行环境和变量预先销毁了,然后在等待线程执行完毕时注定出错!
以为自己算是一个码字高手了,但还是漫不经心的犯各种小问题。
View Code
以为自己算是一个码字高手了,但还是漫不经心的犯各种小问题。
#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
相关文章推荐
- C# WinForm编程TabControl控件的标签TabPage怎么做成图片
- OpenGL入门学习——第五课 三维的空间变换
- OpenGL入门学习——第四课 颜色的选择
- FusionCharts的updateChartXML方法
- linux下配置php环境
- javascript的函数arguments属性和callee调用递归
- OpenGL入门学习——第三课 绘制几何图形的一些细节问题
- 马云将出任UCWeb董事 俞永福:与阿里的关系好过腾讯 百度
- 微信公众平台消息接口开发(12)消息接口Bug
- android ImageView scaleType属性
- 查看oracle数据库的连接数以及用户
- Leetcode Subsets
- tomcat7 登陆密码和账号
- 微信公众平台消息接口开发(11)地理位置查询 当地天气及附近商家
- JAXB
- UVa 10280 Old Wine Into New Bottles / 完全背包
- HDFS文件的tail
- C语言基础
- Centos 6.4添加国内163源
- SpringMVC强大的数据绑定(2)——第六章 注解式控制器详解