C ++ MultiThreading块主线程

时间:2014-03-18 22:39:09

标签: c++ multithreading

我尝试在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 ++中的教程。

1 个答案:

答案 0 :(得分:3)

您可以使用新的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;
}

希望有所帮助

相关问题