Safely toggle a variable, returning the previous value
#include <atomic.h> unsigned atomic_toggle_value( volatile unsigned * loc, unsigned bits );
- A pointer to the location whose bits you want to toggle.
- The bits that you want to change.
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The atomic_toggle_value() function is a thread-safe way of doing an (*loc) ^= bits operation.
The atomic_*() functions are guaranteed to complete without being preempted by another thread, even in a symmetric-multiprocessing system. When modifying a variable shared between a thread and an interrupt, you must either disable interrupts or use the atomic_*() functions.
The atomic_*() functions are also useful for modifying variables that are referenced by more than one thread (that aren't necessarily in the same process) without having to use a mutex.
The previous value of loc's contents.
To safely toggle the 0xdeadbeef bits in a flag:
#include <atomic.h> … volatile unsigned flags; unsigned previous; … previous = atomic_toggle_value( &flags, 0xdeadbeef );