Are there functions for performing atomic operations (like increment / decrement of an integer) etc supported by C Run time library or any other utility libraries?
If yes, what all operations can be made atomic using such functions?
Will it be more beneficial to use such functions than the normal synchronization primitives like mutex etc?
OS : Windows, Linux, Solaris & VxWorks
Prior to C11
The C library doesn’t have any.
On Linux, gcc provides some — look for
__sync_fetch_and_add,__sync_fetch_and_sub, and so on.In the case of Windows, look for
InterlockedIncrement,InterlockedDecrement``,InterlockedExchange`, and so on. If you use gcc on Windows, I’d guess it also has the same built-ins as it does on Linux (though I haven’t verified that).On Solaris, it’ll depend. Presumably if you use gcc, it’ll probably (again) have the same built-ins it does under Linux. Otherwise, there are libraries floating around, but nothing really standardized.
C11
C11 added a (reasonably) complete set of atomic operations and atomic types. The operations include things like
atomic_fetch_addandatomic_fetch_sum(and*_explicitversions of same that let you specify the ordering model you need, where the default ones always usememory_order_seq_cst). There are alsofencefunctions, such asatomic_thread_fenceandatomic_signal_fence.The types correspond to each of the normal integer types–for example,
atomic_int8_tcorresponding toint8_tandatomic_uint_least64_tcorrsponding touint_least64_t. Those aretypedefnames defined in<stdatomic.h>. To avoid conflicts with any existing names, you can omit the header; the compiler itself uses names in the implementor’s namespace (e.g.,_Atomic_uint_least32_tinstead ofatomic_uint_least32_t).