2013-12-18 46 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线程实现。

相关问题