【问题标题】:C++ MultiThreading block main threadC++多线程阻塞主线程
【发布时间】:2014-03-18 22:39:08
【问题描述】:

我尝试在 C++ 程序中设置超时:

  ...
void ActThreadRun(TimeOut *tRun)
{
    tRun->startRun();
}
  ...
void otherFunction()
{
TimeOut *tRun = new TimeOut();
std::thread t1 (ActThreadRun, tRun);
t1.join();    

    while(tRun->isTimeoutRUN())
    {
       manageCycles();
    }
 }
  ...

3 秒后超时,tRun->isTimeoutRUN() 改变其状态。

但是如果我“join”线程,我会阻塞程序,所以它会等待 3 秒再继续,所以它永远不会进入我的 while 循环......

但如果我不“join”线程,线程永远不会超时,tRun->isTimeoutRUN() 永远不会改变,所以它会无限运行。

我不擅长线程,所以我请求你的帮助,因为我不懂 C++ 中的教程。

【问题讨论】:

  • 尝试在 while 循环中添加内存屏障。编译器可能会将值放入寄存器

标签: c++ multithreading


【解决方案1】:

您可以使用新的 C++11 工具

// thread example
#include <iostream>       // std::cout
#include <thread>         // std::thread

void sleep() 
{
    std::chrono::milliseconds dura( 2000 );
    std::this_thread::sleep_for( dura );//this makes this thread sleep for 2s
}

int main()
{
      std::thread timer(sleep);// launches the timer
      int a=2;//this dummy instruction can be executed even if the timer thread did not finish 
      timer.join();            // wait unil timer finishes, ie until the sleep function is done
      std::cout<<"Time expired!";
      return 0;
}

希望有帮助

【讨论】:

  • 但是我必须在 join 和 std::cout 之间做一些事情,这是一个 While 循环,break 是我线程中的一个方法调用...
  • 如果你在加入和cout之前有事要做
  • 我想做的线程只是我的程序的一个超时。所以我可以这样做,当 timeOut 在这里时,它会停止循环。但是当我调用 Join 时,它总是阻塞主线程,所以我无法继续工作,即使使用你的方法
  • 然后你可以启动一个线程并在里面调用超时。那么主线程不会受到影响
猜你喜欢
  • 2018-02-16
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
  • 2016-09-25
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多