Question

Say there is:

unsigned char byte = someValue;

What I need, is to perform an atomic CAS (compare and swap) operation on some two adjacent bits in byte, say the fourth and the fifth.

For sure, there is no way to address something shorter than a byte, but there is a CAS function for a byte, so the following:

unsigned char expected = expectedValue;
unsigned char desired  =  desiredValue;
// atomic CAS operation for byte
__atomic_compare_exchange_n( &byte, &expected, desired, 0, std::memory_order_seq_cst, std::memory_order_seq_cst );

will atomically compare byte with expected, if those are EQUAL, will assign desired to byte and return true, otherwise (i.e. if byte is NOT EQUAL to expected), it will assign byte to expected and return false.

Thus, if it were a CAS operation for byte, where the comparison is done not by just checking the EQUALITY, but doing some bitwise operation, like bitwise-and or bitwise-or, then it would be possible to do CAS for bits.

So the question turns to be if there is a CAS operation for bytes which, when comparing, looks not for the equality, but to some bitwise operation like bitwise-and or bitwise-or?

Was it helpful?

Solution

[is there] a CAS operation for bytes which, when comparing, looks not for the equality, but to some bitwise operation like bitwise-and or bitwise-or?

In C++, the only Compare And Swap operation checks for equality. So the answer is a flat no.

Additionally, I don't know a single CPU that behaves otherwise (though there might be in the microprocessor / DSP categories, who knows, some can do really weird, specialized things).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top