【问题标题】:Creating vector<thread>创建向量<thread>
【发布时间】:2014-06-27 09:16:34
【问题描述】:

我只是想创建一个std::vector 的线程并运行它们。

代码:

thread t1(calc, 95648, "t1");
thread t2(calc, 54787, "t2");
thread t3(calc, 42018, "t3");
thread t4(calc, 75895, "t4");
thread t5(calc, 81548, "t5");

vector<thread> threads { t1, t2, t3, t4, t5 };

错误:“function std::thread::thread(const std::thread &)”(在“C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\thread”的第 70 行声明) 不能被引用——它是一个被删除的函数

thread(const thread&) = delete;

似乎是什么问题?

【问题讨论】:

    标签: c++


    【解决方案1】:

    由于线程不可复制,但可移动,我推荐以下方法:

    std::vector<std::thread> threads;
    
    threads.emplace_back(calc, 95648, "t1");
    threads.emplace_back(calc, 54787, "t2");
    threads.emplace_back(calc, 42018, "t3");
    threads.emplace_back(calc, 75895, "t4");
    threads.emplace_back(calc, 81548, "t5");
    

    【讨论】:

    • 谢谢你的工作!你能解释一下为什么我的代码不起作用以及你的代码是做什么的吗?
    • 因为thread对象不能被复制(当你将一个值插入到向量中时,它会被复制),但是使用emplace,它是直接在向量本身就地创建的。
    【解决方案2】:

    你可以使用:

    vector<thread> threads 
    { 
        std::move(t1),
        std::move(t2),
        std::move(t3),
        std::move(t4),
        std::move(t5) 
    };
    

    【讨论】:

    • 正确 - 复制构造函数被删除(复制线程意味着什么?)但允许移动一个。
    • 执行此操作后,我收到以下错误:C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xmemory0(593): error C2280: 'std::thread:: thread(const std::thread &)' : 试图引用已删除的函数
    • C++ 是否神奇地发明了可移动的初始化列表? 2038 年是哪一年?
    • @KerrekSB:刚刚删除了错误的解决方案,谢谢。
    【解决方案3】:

    禁止复制thread 对象。允许移动。但是你可以使用shared_ptr 来解决这个问题。

    我最喜欢使用线程向量的方式是通过共享指针。

    std::vector<std::shared_ptr<std::thread>> threads;
    

    以这种方式使用它们总是可以足够灵活地扩展向量(向量过去是可扩展的)。

    threads.push_back(std::shared_ptr<std::thread>(new std::thread(&some_fn)));
    

    对于您的代码,如下所示:

    using namespace std;
    
    shared_ptr<thread> t1 = make_shared<thread>(calc, 95648, "t1");
    shared_ptr<thread> t2 = make_shared<thread>(calc, 54787, "t2");
    shared_ptr<thread> t3 = make_shared<thread>(calc, 42018, "t3");
    shared_ptr<thread> t4 = make_shared<thread>(calc, 75895, "t4");
    shared_ptr<thread> t5 = make_shared<thread>(calc, 81548, "t5");
    
    vector<shared_ptr<thread>> threads { t1, t2, t3, t4, t5 };
    

    【讨论】:

    • 我认为这是对 shared_ptr 的滥用。这里不涉及共享所有权。
    • 可能有人要求提供该线程的引用(例如线程池)。这没有在问题中指定。那么这将是一个问题,如果你给出一个 c 引用,如果不立即需要它可能会失败。对我来说,这通常可以减轻在大型框架中处理遗留代码的痛苦。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 2012-04-14
    • 1970-01-01
    相关资源
    最近更新 更多