将原子变量传递给函数

Passing an atomic variable to a function

本文关键字:函数 变量      更新时间:2023-10-16

我正试图将一个原子变量传递给一个函数,如下所示:

 // function factor receives an atomic variable 
 void factor(std::atomic<int> ThreadsCounter)
 {
  .........
 }

 // main starts here
 int main()
 {
 // Atomic variable declaration
 std::atomic<int> ThreadsCounter(0);
 // passing atomic variable to the function factor through a thread
 Threadlist[0] = std::thread (factor, std::ref(ThreadsCounter));
 Threadlist[0].join();
 return 0;
 }

当运行上面的代码时,我得到了以下错误:

错误2错误C2280:"std::atomic::atoic(const std::原子&)":试图引用已删除的函数c:\program files(x86)\microsoft visual studio 12.0\vc\include\functional 1149 1 klu_actor

有人知道怎么解决这个问题吗?非常感谢你的帮助。

函数factor按值取其ThreadsCounter参数,而std::atomic不可复制构造。

即使您绑定了对线程函数的引用,它也试图创建一个副本来传递函数。