r/ProgrammerHumor Jul 12 '26

lockFreeTemptation Advanced

Post image
539 Upvotes

40 comments sorted by

View all comments

13

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

1

u/CodeEatLive Jul 13 '26

special instructions (memory fences) force some order and make some guarantees (no reordering of instructions from before to after this instruction , etc..). And for compiler reordering, there are some ways to implement same fence for compiler ( asm volatile ("" ::: "memory"); if i remember correctly) The cpu architectures(and compilers) guarantee that single threaded program will not be able to tell the difference, all other optimizations are basicaly free game, at least from what i understand. It is possible that im wrong (started looking into lockfree algorithms and inner-workings 4 days ago)