I'm not sure how to use the atomic_bool type from stdatomic.h in C. I'm able to find a lot of C++ examples but nothing regarding C.
A bit of context : I'm trying to have an atomic boolean to be able to stop the infinite loop of one of my threads.
The first thing I did was the following :
#include <stdatomic.h>
static atomic_bool logger_thread_running = true;
And I loop like this :
while(logger_thread_running)
When I want to stop my thread, I simply do :
logger_thread_running = false;
It seems to work fine, but I need to be sure it's really atomic. I've seen on the internet some people initializing their bool like this :
static atomic_bool logger_thread_running = ATOMIC_VAR_INIT(true);
And using atomic_store
and atomic_load
to use the boolean. Should I use those instead or is it atomic already the way I did it ? And if it's not atomic already, why does gcc compile it without throwing any warning ? Thanks!
Edit : I don't want the overhead of a mutex here. I don't care if a few more loop iterations occur because the kernel's thread scheduling decided so.