【问题标题】:Using a vector of thread in another thread : error attempting to reference a deleted function在另一个线程中使用线程向量:尝试引用已删除函数时出错
【发布时间】:2014-06-11 16:40:16
【问题描述】:

我正在尝试将向量发送到另一个线程函数的参数:

void foo(){}
const int n = 24;
void Thread_Joiner(std::vector<thread>& t,int threadNumber)
{
    //some code
}
int main()
{
    std::vector<thread> threads(n, thread(foo));
    thread Control_thread1(Thread_Joiner, threads, 0);//error
    thread Control_thread2(Thread_Joiner, threads, 1);//error
    //...
}

上面的代码给出了这个错误:

: attempting to reference a deleted function

我检查了std::thread的头文件似乎删除了复制构造函数:thread(const thread&amp;) = delete;

std::thread 有一个移动构造函数,但我认为在这种情况下使用移动没有帮助,因为Control_thread1Control_thread2 使用相同的vector

如果我使用 thread **threads;... 而不是 vector 它可以正常工作,但我不想使用 pointers

我该怎么办?!

【问题讨论】:

    标签: c++ multithreading c++11 stl stdthread


    【解决方案1】:

    std::thread 复制用于绑定的参数。使用std::ref 包含它作为参考:

    std::thread Control_thread1(Thread_Joiner, std::ref(threads), 0);
    std::thread Control_thread2(Thread_Joiner, std::ref(threads), 1);
    

    【讨论】:

    • @xyz 你的vector的构造函数也试图复制一个thread(foo)对象。
    • 这就是我该如何解决的问题?!使用vector&lt;thread*&gt; ?
    • @xyz 是的,但最好使用智能指针:std::vector&lt;std::shared_ptr&lt;std::thread&gt;&gt; threads(n, std::make_shared&lt;std::thread&gt;(foo))。如果您不打算将向量扩展到超过其声明的大小,请使用std::array&lt;24, std::shared_ptr&lt;std::thread&gt;&gt;
    • @xyz 其实你只需要std::vector&lt;std::thread&gt; threads; for (auto&amp; th : threads) th = std::thread(foo);
    • @xyz 我知道,但我建议在没有 shared_ptr 的情况下使用它是错误的。 See this example.
    猜你喜欢
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2023-01-04
    • 1970-01-01
    相关资源
    最近更新 更多