【问题标题】:Boost Multithreading提升多线程
【发布时间】:2010-05-13 17:25:43
【问题描述】:

谁能告诉这里发生了什么?当我尝试调试代码并且控件在第 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. }

【问题讨论】:

    标签: c++ multithreading boost


    【解决方案1】:

    可能您的调试器实际上正在并行执行多个线程,这就是它似乎来回跳跃的原因。尝试从调试器打印线程 ID,您可能会在每个停止处看到不同的数字。

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2021-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-07
        • 1970-01-01
        • 1970-01-01
        • 2011-06-08
        相关资源
        最近更新 更多