将const引用传递给线程

时间:2020-06-09 18:56:38

标签: c++ multithreading reference

我需要将一些数据传递给以下方法:

thread::thread(_Fp&& __f, _Args&&... __args)

但是,我的数据是const&,并且没有复制或移动构造函数。我想知道如何使其工作?

1 个答案:

答案 0 :(得分:1)

使用std::cref

此操作“包含引用”,因此您可以绕开std::thread复制参数的趋势。

然后有责任确保这样做是线程安全的。

void foo(const int&);

int main()
{
   const int myThing = 42;

   std::thread t(&foo, std::cref(myThing));
   t.join();
}

the std::thread constructor的cppreference页面上提到了这一点:

线程函数的参数按值移动或复制。如果需要将引用参数传递给线程函数,则必须将其包装(例如,使用std::refstd::cref)。

…以及一个示例(类似)。