首页 > 技术文章 > #include <boost/thread.hpp>

denggelin 2016-08-14 09:47 原文

 

在这个库最重要的一个类就是boost::thread,它是在boost/thread.hpp里定义的,用来创建一个新线程。它已经被纳入C++标准库中。

 

小结:新一代C++标准将线程库引入后,将简化多线程开发。

 

 1 #include <iostream>
 2 #include <boost/thread.hpp>
 3 
 4 void wait(int sec)
 5 {
 6     boost::this_thread::sleep(boost::posix_time::seconds(sec));//boost的sleep可以跨平台,但是windows的sleep不可以跨平台
 7 }
 8 
 9 void threadA()
10 {
11     for (int i = 0; i < 10; i++)
12     {
13         wait(1);
14         std::cout << i << std::endl;
15     }
16 }
17 
18 void threadB()
19 {
20     try
21     {
22         for (int i = 0; i < 10; i++)
23         {
24             wait(1);
25             std::cout << i << std::endl;
26         }
27     }
28     catch (boost::thread_interrupted &)
29     {
30 
31     }
32 }
33 
34 void main()
35 {
36     boost::thread t(threadA);
37     wait(3);
38     t.interrupt();//结束进程
39     t.join();
40 }

 

推荐阅读