Hacker News new | past | comments | ask | show | jobs | submit login

Remember kids: Bitfields are not thread-safe!



Gotta one-up your pedantry here: kids, "atomic" and "thread-safe" are not the same thing. Bit operations are not in general atomic (though on some architectures they can be), but atomic operations themselves are only a requirement, and not sufficient for, thread safety. Thread safety is an architectural property. You can write terribly racy code using 100% atomic operations.


Nothing in C is thread-safe out of the box.


Certain operations are, such as static variable initialization (which I believe is done during program startup in C).


Static variable initialisation that is not initialisation of such variables local to functions is performed before the program starts running, so there cannot be multiple threads.

I can't remember the case in C, but in C++ the initialisation of a function local static variable is guaranteed to be thread-safe.


It doesn't matter that much whether the variable is global or local, but rather what the valid initializers are.

In C, all statics can only be initialized with compile-time constants. Thus, they can all be initialized before anything in the program starts running (indeed, there's no code initializing them in most implementations - they are just bytes in the data segment).

In C++, initializers can be arbitrary expressions, which means that an initializer for a global variable can spawn a thread, and that thread might still be running when another global is being initialized with a different expression that is not a compile-time constant. There are no thread safety guarantees wrt those kinds of conflicts, for either globals or locals. But for static locals with runtime initializers, the evaluation of initializer is deferred until execution actually reaches the definition of that variable - and thus C++ has a special provision for thread-safe synchronization if that happens on two different threads concurrently.


> Static variable initialisation that is not initialisation of such variables local to functions is performed before the program starts running, so there cannot be multiple threads.

you forget the dlopen case :)


> I can't remember the case in C, but in C++ the initialisation of a function local static variable is guaranteed to be thread-safe.

Only in C++11 onwards.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: