2013-03-16 80 views
13

C++ 11矢量STD的線程::

我試圖讓std::threadvector秒。我可以結合以下三點。

1)根據http://en.cppreference.com/w/cpp/thread/thread/threadthread的默認構造函數創建一個

thread object which does not represent a thread.

2.)根據http://en.cppreference.com/w/cpp/thread/thread/operator%3Dthreadoperator=

Assigns the state of [the parameter, which is a thread rvalue reference] to [the calling thread] using move semantics.

3.)根據 http://en.cppreference.com/w/cpp/container/vector/vector,將 只有一個尺寸類型的變量傳遞給一個向量構造函數將解析CT

the container with [the specified number of] value-initialized (default constructed, for classes) instances of T. No copies are made.

所以,我這樣做:

#include <iostream> 
#include <thread> 
#include <vector> 

void foo() 
{ 
    std::cout << "Hello\n"; 
    return; 
} 

int main() 
{ 
    std::vector<std::thread> vecThread(1); 
    vecThread.at(0) = std::thread(foo); 
    vecThread.at(0).join(); 
    return 0; 
} 

這運行正常的VC11和g++ 4.8.0 (online compiler here)如下面所示:

控制檯輸出:

Hello 

然後我試圖它在鐺3.2,通過切換在同一網頁上,這給編譯器菜單:

stderr: 
pure virtual method called 
terminate called without an active exception 

當一個線程對象表示一個線程超出範圍是join() ED或detach()之前該程序將被迫終止。我有join()vecThread.at(0),所以留在問題的唯一事情是臨時線程

std::thread(foo);

vecThread.at(0) = std::thread(foo);

分配。

但是,根據Web引用,只能通過移動線程右值引用來分配線程。我想不出任何方法來join()detach()一個臨時線程對象。

所以如果鏗鏘的輸出是正確的,那麼threadoperator=有什麼用?或者這是一個鏗鏘編譯器錯誤?

In g ++ 4.8。0,改變線

vecThread.at(0) = std::thread(foo)

vecThread.at(0) = std::thread{foo}

(用大括號替換括號內)仍然給出了預期Hello輸出。

然而,轉產到vecThread.at(0) = {foo}使得抱怨:

G ++ 4.8.0對大括號投訴:

error: converting to 'std::thread' from initializer list would use explicit constructor 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(); _Args = {}]' vecThread.at(0) = {foo};

是太先進了,我不知道這意味着什麼。

使在鐺相同的變化給出了更先進:

鐺3.2的牙齒矯正器上抱怨:

error: no viable overloaded '=' 
vecThread.at(0) = {foo}; 
... 
note: candidate function not viable: cannot convert initializer list 
argument to 'const std::thread' 
thread& operator=(const thread&) = delete; 
... 
note: candidate function not viable: cannot convert initializer list 
argument to 'std::thread' 
thread& operator=(thread&& __t) noexcept 

,我不知道是什麼意思要麼。

我不能使用VC11,以證實上述

vecThread.at(0) = {foo}

問題,因爲VC11,爲2012年11月CTP編譯器,不支持標準庫的統一初始化語法。

+0

你用'-pthread'編譯了嗎?代碼看起來很好,儘管有點冗長。 – 2013-03-16 04:24:08

+0

你的意思是我應該在編譯器的'compiler/interpreter'參數文本字段中添加'-pthread'?我將它添加到網頁的文本字段的原始編譯器/解釋器參數中,使其在叮噹聲中成爲'-std = C++ 11 -Wall -W -pedantic -O2 -pthread',但獲得與'terminate'被調用相同的結果。 – CodeBricks 2013-03-16 04:43:02

+0

那麼,[編碼](http://ideone.com/4B2Elt)適用於編譯時用'-std = C++ 0x -pthread' ... – 2013-03-16 04:46:43

回答

7

你的第一個例子是正確的。拋出一個異常是已知的bug,當你用libstdC++使用clang時。要解決它,你必須安裝libC++(llvm版本的C++庫)。看到的libc編譯的一個例子下面++

#include <thread> 

int main() 
{ 
    std::thread t([]() {}); 
    t.join(); 
    return 0; 
} 

$ clang++ -std=c++11 -stdlib=libc++ main.cpp -o main -lc++ -lsupc++ -lpthread

P.S.請參閱here,爲什麼還需要標記-lsupc++