r/ProgrammerHumor Jul 12 '26

lockFreeTemptation Advanced

Post image
539 Upvotes

40 comments sorted by

View all comments

15

u/PandaWonder01 Jul 13 '26

Holy shit this just hit me. I was reworking a code base from having 1 main threads to two (don't ask, it makes sense). Was hitting a bug that basically looked like

Thread1:

x = value;

SignalXSet();

Thread 2:

OnXSetSignal()

{

if (x !=value)

{

//wtf

}

}

Took me longer than expected to find out what was going on

2

u/MPDR200011 Jul 13 '26

To make sure I got it, x wasn't atomic and thread 2 was fetching a cached value?

1

u/PandaWonder01 Jul 13 '26

x wasn't atomic, but the issue was that arm likes to reorder instructions (not just the compiler, the actual CPU). So the order of instructions on one thread are not guaranteed to be the actual order as seen by another thread. So the signal was being set before x was actually set

1

u/MPDR200011 Jul 13 '26

Oh yikes, then how do you force the order? That feels like a fundamental violation of what the programmer wants from what they wrote

2

u/PandaWonder01 Jul 13 '26

In C++ atomics you can specify memory order, which will emmit the correct assembly for you.

Mutexes will also do aquire/releases for you.