2014-01-23 27 views
0

我正在學習使用線程。而且我發現我可以使用下面的a thread related problm

mutex mx; 

void func(int id) 
{ 
    mx.lock(); 
    cout << "hey , thread:"<<id << "!" << endl; 
    mx.unlock(); 
} 
int main(){ 
    vector<thread> threads; 
    for(int i = 0 ; i < 5 ; i++) 
     threads.emplace_back(thread(func , i)); 
    for(thread & t : threads) 
     t.join(); 
    return 0; 
} 

,而我不能做的main()

for(int i = 0 ; i < 5 ; i ++) 
{ 
    thread t(func , i); 
    threads.emplace_back(t); 
} 

任何人能解釋這一點?

非常感謝

+0

你收到了哪些錯誤信息? –

+1

當使用'emplace_back'時,元素被構造就位。所有你想傳遞的是構造函數的參數,而不是創建一個不必要的對象。 – chris

回答

2

你需要移動的對象:

thread t(func, i); 
threads.push_back(std::move(t)); 

emplace也可以,但是push_back是習慣在這種情況下。當然還有#include <utility>

+0

我試過這個,它工作。謝謝 。我從線程的引用中看到「copy [deleted](3)thread(const thread&)= delete;」的文檔 – chenglg