I am trying to write a simple C++ application that uses threads and only has to manage a couple of shared variables between the threads. In order to do that simply I decided I would just make these variables std::atomic
so I don't have to worry about manually locking and unlocking things.
I tried to start with a simple example where I create an atomic
variable in main and pass it to the thread. I was surprised when I attempted to compile it and got a bunch of barely decipherable template related compilation errors.
Passing an atomic by reference:
#include <atomic>
#include <thread>
// Causes an ugly compiler error
void func(std::atomic<int>& i) {
// Do something that uses "i" in the thread
}
int main() {
std::atomic<int> i;
std::thread t(func, i);
// Do something that uses "i" in main
t.join();
}
However if I simply pass the atomic variable by pointer it does work.
Passing an atomic by pointer:
#include <atomic>
#include <thread>
// Compiles fine
void func(std::atomic<int>* i) {
// Do something that uses "i" in the thread
}
int main() {
std::atomic<int> i;
std::thread t(func, &i);
// Do something that uses "i" in main
t.join();
}
What exactly is happening here? The error (too long to post here, but you can compile it and see) seems to say something about std::atomic
not having a copy constructor... but I'm passing it by reference. Why on earth would it be trying to make a copy when passed by reference?