提升多线程技术

4

有人能告诉我这里发生了什么吗?当我尝试调试代码并且控制权在第15行的thread()函数时,它跳过了第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. }
2个回答

5

可能你的调试器实际上是同时步进了几个线程,这就是为什么它看起来会来回跳动。尝试从你的调试器中打印线程 ID,你可能会在每次停止时看到不同的数字。

调试中出现奇怪跳跃的另一个原因是代码被优化了。如果是这样的话,源代码顺序不一定与编译后的代码匹配。


0

当它跳跃时,你的输出是什么样子?看起来可能是多线程问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接