I have a thread that I want to sit in a loop until I'm ready to exit the program, at which point I want it to break out of the loop and exit so I can call std::thread::join on it. In the days of c++03, I would just use a bool protected by a lock in order to tell the thread when to exit. This time I thought I would take advantage of the new atomics library (specifically std::atomic_bool), but I'm having trouble. Below is my test case:
#include <atomic>
#include <thread>
#include <cstdio>
using namespace std;
void setBool(atomic_bool& ab)
{
ab = true;
}
int main()
{
atomic_bool b;
b = false;
thread t(setBool, b);
t.join();
printf("Atomic bool value: %d\n", b.load());
return 0;
}
The declaration of thread t spits out this monstrosity when I try to compile. The central part of the error seems to be:
invalid initialization of non-const reference of type ‘std::atomic_bool&’ from an rvalue of type ‘std::atomic_bool’
Why can I not get a reference to an atomic_bool? What should I do instead?