multithreading - 为什么我不能像这样动态创建线程向量

标签 multithreading c++11

为什么动态创建线程向量是错误的?我收到编译错误

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xmemory0(593):错误 C2280:'std::thread::thread(const std::thread &)':试图引用已删除的函数

其次是很多其他的东西。

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

using std::vector;
using std::thread;
using std::cout;

class obj_on_thread {
public:
    void operator()()
    {
        std::cout << "obj on thread\n";
    }
};

void function_on_thread() {
    std::cout << "function on thread\n";
}

auto named_lambda = []() { std::cout << "named_lambda_on_thread\n"; };

int main(){
    obj_on_thread obj;

    vector<thread> pool {
        thread{ obj },
        thread{ function_on_thread },
        thread{ named_lambda },
        thread{ []() { cout << "anonymous lambda on thread\n"; } }
    };
    cout << "main thread\n";

    for(auto& t : pool)
    {
        if (t.joinable())
        {
            cout << "Joinable = true";
            t.join(); //if called must be called once.
        }
        else
        {
            cout << "this shouldn't get printed, joinable = false\n";
        }
    }
    for (auto& t : pool)
    {
        if (t.joinable())
        {
            cout << " This won't be printed Joinable = true";
        }
        else
        {
            cout << "joinable = false thread are already joint\n";
        }
    }

    return 0;
}

最佳答案

std::vector的构造函数使用 initializer_list要求元素是可复制构造的,因为 initializer_list本身要求(它的底层“存储”被实现为一个复制构造的临时数组)。 std::thread不可复制构造(此构造函数被删除)。

http://en.cppreference.com/w/cpp/utility/initializer_list

The underlying array is a temporary array, in which each element is copy-initialized...



没有解决这个问题的好方法 - 您不能一次初始化所有线程,但您可以使用(多次调用,每个线程一个 - 不幸的是):
  • emplace_back() :
    pool.emplace_back(obj);
    
  • push_back()带有右值:
    pool.push_back(thread{obj});
    
  • push_back()与明确 move() s:
    auto t = thread{obj};
    pool.push_back(std::move(t));
    
  • 关于multithreading - 为什么我不能像这样动态创建线程向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27167968/

    相关文章:

    C++11:为什么 std::condition_variable 使用 std::unique_lock?

    c++ - 用于高性能应用程序的多线程日志记录

    Delphi:线程作业的线程列表 - 排队

    java - 是否可以利用Stream API提供的并行性来调用固定数量的相互独立的方法?

    c - Qt多线程应用程序卡住并且多个线程等待相同的互斥体

    c++ - 使用 std::function 参数重载函数:为什么从未调用 const 方法?

    c++ - Clang 候选模板被忽略 : substitution failure (also fails to compile with gcc, VC 工作正常)

    c++ - C 和 C++ 编译器何时隐式地将 float 转换或提升为 double ?

    c++ - GCC 4.7 从初始化器列表初始化 unique_ptrs 容器失败

    c++ - libpqxx 库中没有 pqxx::tuple 吗?