F4K*_*4Ke 2 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();
}
}
...
Run Code Online (Sandbox Code Playgroud)
超时在 3 秒后完成,并tRun->isTimeoutRUN()更改其状态。
但是如果我“ join”线程,我会阻塞程序,所以它会在继续之前等待 3 秒,所以它永远不会进入我的 while 循环......
但是如果我不“ join”线程,线程永远不会超时,tRun->isTimeoutRUN()永远不会改变,所以它会无限运行。
我不擅长线程,所以我在寻求你的帮助,因为我不理解 C++ 中的教程。
您可以使用新的 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;
}
Run Code Online (Sandbox Code Playgroud)
希望有帮助