c++c++11atomic

Passing an atomic variable to a function


I am trying to pass an atomic variable to a function as follow:

 // 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;
 }

When running the above code, I was getting the following error:

Error 2 error C2280: 'std::atomic::atomic(const std::atomic &)' : attempting to reference a deleted function c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional 1149 1 klu_factor

Anyone knows how to fix this ? your help is much appreciated.


Solution

  • The function factor takes its ThreadsCounter parameter by value, and std::atomic is not copy constructible.

    Even though you bound a reference to your thread function, it's attempting to create a copy to pass the function.