矢量std :: threads

Cod*_*cks 14 c++ multithreading vector c++11 stdthread

C++ 11

我试图做出vectorstd::thread秒.以下三点的组合说我可以.

1.)根据http://en.cppreference.com/w/cpp/thread/thread/thread, thread默认构造函数创建一个

不代表线程的线程对象.

2.)根据http://en.cppreference.com/w/cpp/thread/thread/operator%3D,threadoperator=

使用移动语义将[参数,即线程右值引用]的状态分配给[调用线程].

3.)根据 http://en.cppreference.com/w/cpp/container/vector/vector,仅将大小类型变量传递给向量构造函数

具有[指定数量]的值初始化(对于类的默认构造)T实例的容器.没有复制.

所以,我这样做了:

#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;
}
Run Code Online (Sandbox Code Playgroud)

这在VC11和g ++ 4.8.0(在线编译器)中按预期运行,如下所示:

控制台输出:

Hello
Run Code Online (Sandbox Code Playgroud)

然后我在clang 3.2中尝试了它,通过在同一个网页上切换编译器菜单,这给出了:

stderr: 
pure virtual method called
terminate called without an active exception
Run Code Online (Sandbox Code Playgroud)

当一个代表线程的线程对象在join()编辑或detach()编辑之前超出范围时,程序将被强制终止.我有join()ed vecThread.at(0),所以剩下的唯一问题是临时线程

std::thread(foo);

在里面

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

分配.

但是,根据Web引用,只能通过移动线程右值引用来分配线程.我想不出任何方法join()detach()临时线程对象.

所以,如果铛的输出是正确的,那么什么是使用threadoperator=?或者这是一个clang编译器错误?

在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对括号的投诉:

错误:从初始化列表转换为'std :: thread'将使用显式构造函数'std :: thread :: thread(_Callable &&,_ Args && ...)[with _Callable = void(&)(); _Args = {}]'vecThread.at(0)= {foo};

这太先进了 - 我不知道它意味着什么.

在clang中进行相同的更改可以提供更高级的功能:

clang 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
Run Code Online (Sandbox Code Playgroud)

我也不知道这意味着什么.

我无法使用VC11来证实上述内容

vecThread.at(0) = {foo}

问题是因为VC11(截至2012年11月的CTP编译器)不支持标准库上的统一初始化语法.

awe*_*oon 7

你的第一个例子是正确的.当你使用clang和libstdc ++时,抛出异常是一个已知的错误.要解决它,您必须安装libc ++(llvm版本的c ++库).请参阅下面的使用libc ++进行编译的示例

#include <thread>

int main()
{
    std::thread t([] () {});
    t.join();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

PS看到这里,为什么还要求旗帜-lsupc++.