Jos*_*h16 4 c++ multithreading boost
谁能告诉我们这里发生了什么?当我尝试调试代码,当控件处于线程()函数在15行,它跳过了第16行移动到第17行并返回线16为什么不是由线动线?
1. #include <boost/thread.hpp>
2. #include <iostream>
3.
4. void wait(int seconds)
5. {
6. boost::this_thread::sleep(boost::posix_time::seconds(seconds));
7. }
8.
9. boost::mutex mutex;
10.
11. void thread()
12. {
13. for (int i = 0; i < 5; ++i)
14. {
15. wait(1);
16. mutex.lock();
17. std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl;
18. mutex.unlock();
19. }
20. }
21.
22. int main()
23. {
24. boost::thread t1(thread);
25. boost::thread t2(thread);
26. t1.join();
27. t2.join();
28. }
Run Code Online (Sandbox Code Playgroud)
可能你的调试器实际上并行地执行了几个线程,这就是为什么它似乎来回跳转.尝试从调试器中打印线程ID,您可能会在每个站点看到不同的数字.
在调试中奇怪跳跃的另一个原因是代码是否经过优化.如果是这样,源代码顺序不会与编译的代码匹配