I have some code that copies masked bits into an integer by first clearing them in the target int then ORing them into the int.
Like this:
bitsToSet = 6
targetInt &= ~(1 << bitsToSet)
targetInt |= desiredBitValue << bitsToSet
The problem is that it now needs to be thread safe, and I need to make the operation atomic. I think that using std:atomic<int> would only make each sub-operation atomic but not the operation as a whole.
How can I make the whole operation (including both the &= and the |= operations) atomic?
For example, it would solve the problem for me if I had a function (or better, a macro) like SetBits(TARGET, MASK, VALUE) that would atomically set the MASKed bits in TARGET to VALUE. The MASK and VALUE can already be left-shifted.
My current, non-atomic code is
#define SetBits(TARGET, MASK, VALUE) {(TARGET) &= ~((uint64_t)MASK); (TARGET)|=((uint64_t)VALUE);}