2014-03-18 88 views
1

我儘量讓一個超時的C++程序,就像這樣: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個secondes做的,而tRun->isTimeoutRUN()改變自己的狀態。

但是,如果我「join」線程,我阻止此程序,所以這是等待的時間(3秒)繼續之前,所以它從來沒有在我,而仿羔皮呢去...

但是,如果我不要「join」這個線程,線程永不超時,並且tRun->isTimeoutRUN()永不改變,所以它無限運行。

我不是線程好,所以我問你的幫助,因爲我不明白,在這個教程中C++

泰!

+0

嘗試添加while循環內存屏障。編譯器可以將值放入寄存器 – thisisdog

回答

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

希望幫助

+0

但是我必須在連接和std :: cout之間做一些事情,一個While循環,其中break是一個方法調用在我的線程中... – F4Ke

+0

如果你有東西做之前加入和cout <<「時間過期!」然後將它添加到睡眠函數中,在std :: this_thread :: sleep_for(dura)之後; //這使得該線程睡眠2s。那麼你會:啓動線程,運行計時器,做你想做的事情,然後打印cout。這能解決你的問題嗎? – Gabriel

+0

我想要做的線程只是我的程序的一段時間。所以我可以這樣做,當timeOut在這裏時,它會停止循環。但是,當我打電話加入它總是阻止主線程,所以我不能繼續工作,即使你的方法 – F4Ke