2013-12-18 45 views

回答

2

std::thread::join()不使線程運行。當std::thread對象使用函數對象參數構造時,線程運行。

例如:

std::thread thrd1(doSomething); // Thread starts 
// Some codes... 
thrd1.join(); // Wait for thread exit 
std::thread thrd2; // default constructor 
thrd2 = std::thread(doSomething); 
// blablabla... 
thrd2.join(); 
+0

啊,對不起,你是對的。 –

0

好,C++11線程實際上(據我所知)使用系統主線程設施,用於UNIX系統,它可能會使用POSIX線程。

做的一個簡單的例子,我覺得你想要做的可能是這樣的:

#include <thread> 
#include <iostream> 

// The function run from the thread i.e. "run the thread" part of your question. 
void things_to_do_in_thread() { 
    std::cout << "Hello World" << std::endl; 
} 

int main() { 
    // This create the thread and call the function 
    std::thread my_thread(things_to_do_in_thread); 

    //Join with the main thread 
    my_thread.join(); 

    return 0; 
} 

你也可以給一個lambda-function運行這將是這樣的:

#include <thread> 
#include <iostream> 

int main() { 
    std::thread my_thread([](){ 
     std::cout << "Hello world" << std::this_thread::get_id() << std::endl; 
    }); 

    my_thread.join(); 
} 

我希望這是你所要求的,它會幫助你熟悉C++11中的std線程實現。

相關問題