Spurious failures of thread functions

C11’s thread interface was not very clear on failure conditions that some functions might encounter. It was not clear that wait functions for conditional variables (cnd_t) and tentative locking of mutexes (mtx_t) may fail spuriously, that is with not apparent reason for the caller. By lack of such a specification, it was not clear how C11 threads could be realized by POSIX threads, e.g.

Allowing spurious wakeups is particularly important for the wait functions, because it makes implementing the cnd_t type much easier, in particular for the special case that the caller of cnd_signal or cnd_broadcast does not hold the lock on the corresponding mutex. On the other hand, from an application point of view this does not change much. Even without spurious wakeups, a thread that called `cnd_wait`, e.g, must in any case check the real condition they are interested in.

Continue reading “Spurious failures of thread functions”

compare exchange compares memory and not value

In C11, 7.17.7.4, introduces atomic_compare_exchange generic functions. These are precious tools when using atomics: they allow to conditionally store new data in an atomic variable and to retrieve a previous value of it, eventually. You can see that as a generalization of atomic_fetch_and_add where we are also able to retrieve a counter value and change it at the same time.

C11 stated that the value would be taken into account for the conditional part, that is that the existing value would be compared to a desired value. This works well for arithmetic types, where value and object representation are mostly the same. It works less well if the atomic type is a structure because struct types simply have no equality operator.

Continue reading “compare exchange compares memory and not value”

C17: reformulations for atomic_flag

In C11, there was a problem with the fact that atomic_flag is one of the rare types that is not considered to have a value, but it only has state (clear and set) which is changed via function calls. (mtx_t and cnd_t are other examples of such types.) There was no established relation between these states and the return value of the atomic_flag_test_and_set functions (which is bool).

C17 clears that up by prescribing the return values of atomic_flag_test_and_set

Continue reading “C17: reformulations for atomic_flag”