相关疑难解决方法(0)

在C++ 11中通过引用传递对象到std :: thread

为什么在创建时不能通过引用传递对象std::thread

例如,以下snippit给出了编译错误:

#include <iostream>
#include <thread>

using namespace std;

static void SimpleThread(int& a)  // compile error
//static void SimpleThread(int a)     // OK
{
    cout << __PRETTY_FUNCTION__ << ":" << a << endl;
}

int main()
{
    int a = 6;

    auto thread1 = std::thread(SimpleThread, a);

    thread1.join();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:

In file included from /usr/include/c++/4.8/thread:39:0,
                 from ./std_thread_refs.cpp:5:
/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<void (*(int))(int&)>’:
/usr/include/c++/4.8/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(int&); _Args = {int&}]’ …
Run Code Online (Sandbox Code Playgroud)

c++ pass-by-reference c++11 stdthread

42
推荐指数
3
解决办法
2万
查看次数

矢量std :: threads

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),所以剩下的唯一问题是临时线程 …

c++ multithreading vector c++11 stdthread

14
推荐指数
1
解决办法
2万
查看次数