Domanda

Why does std::atomic_compare_exchange and all its brothers and sisters update the passed expected value?

I am wondering if the are any reasons besides the given simplicity in loops, e.g.: is there an intrinsic function which can do that in one operation to improve performance?

È stato utile?

Soluzione

The processor has to load the current value, in order to do the "compare" part of the operation. When the comparison fails the caller needs to know the new value, to retry the compare-exchange (you almost always use it in a loop), so if it wasn't returned (e.g. by modifying the expected value that is passed by reference) then the caller would need to do another atomic load to get the new value. That's wasteful, because the processor has already loaded the value. You should only be messing about with low-level atomic operations when extreme performance is the only option, so in that case you do not want to perform two operations when one will do.

Altri suggerimenti

is there an intrinsic function which can do that in one operation to improve performance

That can do what, specifically? The instruction has to load the current value to do the comparison, so on a mismatch yielding the current value costs nothing and is pretty much guaranteed to be useful.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top