在另一个线程中使用线程的向量:试图引用已删除的函数时出错

Using a vector of thread in another thread : error attempting to reference a deleted function

本文关键字:线程 引用 删除 函数 出错 另一个 向量      更新时间:2023-10-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&) = delete;

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

如果我用thread **threads;...代替vector,它工作得很好,但我不想使用指针

我该怎么办?!

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

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