将原子变量传递给函数

6
我将尝试按如下方式将原子变量传递给函数:

 // 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::atomic(const std::atomic &)' : 尝试引用已删除的函数 c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional 1149 1 klu_factor 有人知道如何解决吗?非常感谢您的帮助。
1个回答

9
函数factor通过值传递其ThreadsCounter参数,而std::atomic不可复制。
即使将引用绑定到线程函数,它仍然会尝试创建一个副本来传递该函数。

@ Collin Dauphinee,我刚刚尝试将函数修改为'void factor(std::atomic<int> &ThreadsCounter)',但是我得到了相同的错误。 - Anas
1
我刚刚编译并运行了你的测试用例,请再次确认你确实构建了更改。 - Collin Dauphinee
是的,我的错,我修改了源文件但没有修改头文件。现在它可以工作了,谢谢。 - Anas
1
@ Collin Dauphinee,在函数中递增原子变量的最佳方法是什么?抱歉,我还不太了解原子变量。 - Anas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接