2013-03-16 86 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++