Why doesn't C/C++ have an atomic flag test_and_clear()?
The atomic_flag
type in C/C++ provides a minimal set of lock-free atomic operations, including test_and_set()
and clear()
. However, there is no test_and_clear()
operation defined for atomic_flag
.
The reason for this is that test_and_clear()
is not a necessary operation for lock-free synchronization. In fact, it can be implemented using test_and_set()
and clear()
, as follows:
bool test_and_clear(std::atomic_flag& flag) { bool old_value = flag.test_and_set(); flag.clear(); return old_value; }
Since test_and_clear()
can be implemented using other atomic operations, there is no need to include it as a separate operation in the atomic_flag
type.
Another reason why test_and_clear()
is not included in atomic_flag
is that it is not as efficient as test_and_set()
and clear()
. The test_and_set()
operation only needs to read and write a single memory location, while the test_and_clear()
operation needs to read and write two memory locations.
For these reasons, the C/C++ standard does not define a test_and_clear()
operation for atomic_flag
.