2010-05-13 174 views
4

任何人都可以告訴這裏發生了什麼?當我嘗試調試代碼時,以及控件位於第15行的thread()函數中時,它會跳過第16行移動到第17行並返回第16行。爲什麼它不會逐行移動?Boost多線程

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. } 

回答

5

可能你的調試器實際上並行地執行幾個線程,這就是它爲什麼會跳來跳去。嘗試從您的調試器打印線程ID,您可能會在每個站點看到不同的數字。

調試中出現奇怪跳躍的另一個原因是代碼已經優化。如果是這樣,則源代碼順序不會與編譯代碼匹配

0

當您的輸出跳轉時,您的輸出是什麼樣的?它看起來可能是多線程問題。