2017-02-21 28 views
1

我初始化它開始運行的std::thread後(即調用功函數),或者它只是開始運行時我叫join()這是在文檔有點不清楚。在調用join()之前,std :: thread是否運行?

+2

它立即開始運行。對於一個新線程來說,等到其他線程想要加入它時,它纔會毫無意義。 –

+1

線程在運行狀態下創建,所以線程將在join()調用之前執行。並期待你的下一個問題,也許,沒有選擇創建一個處於停止狀態的線程,雖然你可以使用'std :: mutex'或類似的東西來暫停線程。 –

回答

2

當你實例化它,它就會執行。

加入用於使當前線程將等到其他線程執行完畢。

一些示例代碼從http://en.cppreference.com/w/cpp/thread/thread/thread

void f1(int n) 
{ 
    for (int i = 0; i < 5; ++i) { 
     std::cout << "Thread 1 executing\n"; 
     ++n; 
     std::this_thread::sleep_for(std::chrono::milliseconds(10)); 
    } 
} 

void f2(int& n) 
{ 
    for (int i = 0; i < 5; ++i) { 
     std::cout << "Thread 2 executing\n"; 
     ++n; 
     std::this_thread::sleep_for(std::chrono::milliseconds(10)); 
    } 
} 

int main() 
{ 
    int n = 0; 
    std::thread t1; // t1 is not a thread 
    std::thread t2(f1, n + 1); // pass by value 
    std::thread t3(f2, std::ref(n)); // pass by reference 
    std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread 
    t2.join(); 
    t4.join(); 
    std::cout << "Final value of n is " << n << '\n'; 
} 

    Possible output: 
Thread 1 executing 
Thread 2 executing 
Thread 1 executing 
Thread 2 executing 
Thread 1 executing 
Thread 2 executing 
Thread 1 executing 
Thread 2 executing 
Thread 2 executing 
Thread 1 executing 
Final value of n is 5 
1

一旦std::tread創建它是處於運行狀態,其中它可以執行指令。

沒有保證,將在任何給定時間間隔做任何事情,但它做一些事情的可能性會更接近100%作爲間隔變長。

通常情況下,設計生動活潑切實保證,當你起牀到十分之一秒的時間間隔,所有非等待的線程會表現出一定的活性。

相關問題