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

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

  

 1 #include <boost/make_shared.hpp>
 2 #include <boost/thread.hpp>
 3 #include <boost/thread/mutex.hpp>
 4 #include <boost/thread/condition.hpp>
 5 
 6 class simple_thread
 7 {
 8 
 9 public:
10     simple_thread()
11     {
12         m_run_flag = 0;
13     }
14 
15     ~simple_thread()
16     {
17         if (m_thread_grp)
18         {
19             stop();
20 
21             m_thread_grp->join_all();
22 
23             m_thread_grp.reset();
24         }
25     }
26 
27 public:
28     void start()
29     {
30         m_run_flag = 1;
31 
32         m_thread_grp = boost::make_shared<boost::thread_group>();
33 
34         m_thread_grp->create_thread(boost::bind(&simple_thread::thread_proc, this));
35     }
36 
37     void stop()
38     {
39         m_run_flag = 0;
40 
41         m_con_scp.notify_all();
42     }
43 
44     void thread_proc()
45     {
46         std::cout<<"thread_proc starting..."<<std::endl;
47 
48         while (1)
49         {
50             Sleep(10000);
51 
52             if (!m_run_flag)
53             {
54                 break;
55             }
56 
57             boost::mutex::scoped_lock lock(m_mt_scp);
58             m_con_scp.wait(m_mt_scp);
59         }
60 
61         std::cout<<"thread_proc endding...."<<std::endl;
62     }
63 
64 private:
65     int m_run_flag;
66 
67     boost::mutex m_mt_scp;
68     boost::condition m_con_scp;
69     boost::shared_ptr<boost::thread_group> m_thread_grp;
70 };
71 
72 
73 int _tmain(int argc, _TCHAR* argv[])
74 {
75     if (1)
76     {
77         boost::shared_ptr<simple_thread> test = boost::make_shared<simple_thread>();
78         test->start();
79 
80         std::cout<<"object destroying...."<<std::endl;
81     }
82     
83     Sleep(INFINITE);
84 
85     return 0;
86 }
View Code

相关文章:

  • 2021-10-20
  • 2021-10-24
  • 2021-10-16
  • 2021-10-11
  • 2021-10-16
  • 2021-07-26
  • 2022-12-23
  • 2021-06-22
猜你喜欢
  • 2021-08-04
  • 2021-07-15
  • 2021-06-05
  • 2022-12-23
  • 2021-05-15
  • 2021-08-12
  • 2021-05-29
相关资源
相似解决方案