3

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.

ShellCode
  • 1,072
  • 8
  • 17
  • 1
    Looks like it depends on the version, in `C17` it's not needed. https://gustedt.wordpress.com/2018/08/06/c17-obsoletes-atomic_var_init/ – Renat Jul 22 '19 at 09:56
  • 1
    It was not needed in C11 mostly either. – Antti Haapala -- Слава Україні Jul 22 '19 at 10:05
  • 1
    http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2148.htm#dr_485 – Antti Haapala -- Слава Україні Jul 22 '19 at 10:07
  • 2
    "No known implementations use embedded locks, however, and as such there is no technical requirement for the use of the ATOMIC_VAR_INIT macro." – Antti Haapala -- Слава Україні Jul 22 '19 at 10:09
  • Thanks for your comments guys ! Does that mean I should use ATOMIC_VAR_INIT if I want my code to be as portable as possible ? And what about atomic_(store|load) ? Should I use them ? – ShellCode Jul 22 '19 at 10:55
  • 1
    *Does that mean I should use `ATOMIC_VAR_INIT`* No, the requirement in ISO C that a default-initialized static atomic variable also needs to work pretty much precludes any design that would require a non-trivial `ATOMIC_VAR_INIT`. TL:DR: ISO C was trying to allow more implementation options with this idea, but ended up not doing so, and now they're just removing the complexity because nothing ever requires it. – Peter Cordes Jul 22 '19 at 15:48
  • 2
    *And what about atomic_(store|load) ? Should I use them?* No, only `atomic_store_explicit` or load is useful if you want a memory order weaker than seq_cst. Otherwise simple assignment is equivalent to store, and reading the value (lvalue to rvalue conversion) is equivalent to load. – Peter Cordes Jul 22 '19 at 15:50
  • Thank you very much ! :) – ShellCode Jul 22 '19 at 16:08

0 Answers0