C++boostthread学习(一)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C++boostthread学习(⼀)
线程中断
在⼀个线程对象上调⽤ interrupt() 会中断相应的线程,并会在这个线程中抛出⼀个类型为 boost::thread_interrupted 的异常。
如果给定的线程不包含任何中断点,简单调⽤interrupt就不会起作⽤。
每当⼀个线程中断点,它就会检查interrupt是否被调⽤过。
只有被调⽤过了, boost::thread_interrupted 异常才会相应地抛出。
Boost.Thread定义了⼀系列的中断点,例如sleep() 函数,由于sleep() 在这个例⼦⾥被调⽤了五次,该线程就检查了五次它是否应该被中断。
然⽽sleep()之间的调⽤,却不能使线程中断。
⼀旦该程序被执⾏,它只会打印三个标准输出流。
这是由于在main⾥3秒后调⽤ interrupt()⽅法。
因此,相应的线程被中断,并抛出⼀个boost::thread_interrupted 异常。
这个异常在线程内也被正确地捕获,catch 处理是空的。
Boost.Thread定义包括上述 sleep()函数等⼗个中断。
有了这些中断点,线程可以很容易及时中断。
然⽽,他们并不总是最佳的选择,因为中断点必须事前读⼊以检查 boost::thread_interrupted 异常。
C++代码
1. #include <boost/thread.hpp>
2. #include <boost/thread/mutex.hpp>
3.
4. #include <iostream>
5.
6. boost::mutex io_mutex;
7.
8. using namespace std;
9.
10. void wait(int seconds)
11. {
12. boost::this_thread::sleep(boost::posix_time::seconds(seconds));
13. }
14.
15. void interruptedThread()
16. {
17. try
18. {
19. for (int i = 0; i < 5; i++)
20. {
21. wait(1);
22. cout << i << endl;
23. }
24. }
25. catch (boost::thread_interrupted&)
26. {
27. cout << "thread_interrupted exception happened";
28. }
29. }
30.
31. void testInteruptedThread()
32. {
33. boost::thread t(interruptedThread);
34. wait(3);
35. t.interrupt();
36. t.join();
37. }
38.
39. int main(int argc, char* argv[])
40. {
41. testInteruptedThread();
42. return 0;
43. }。