4 ms·
I tried to think how this might go wrong. The part that I can see going wrong is with the 'choosing' array, an optimizer may choose to combine the two writes an
by contravariant 3y ago
I tried to think how this might go wrong. The part that I can see going wrong is with the 'choosing' array, an optimizer may choose to combine the two writes and just write 'false' immediately. I feel like that breaks a lot of reasonable guarantees, but let's run with it.
So basically the problem is that two processes might pick the same number, see the other process with an (outdated) lower number and choosing=false, and go ahead into the critical section.
So basically you need a guarantee that the write to the choosing array lands before picking a number. You can simplify things a bit by simply setting 'number' high instead of using 2 arrays, but still.
- exDM69 3y agoEven if the algorithm "works", it does not guard the critical section correctly. The code that is supposed to go between lock() and unlock() may be executed before the lock is acquired or after it is released because CPU is allowed to reorder anything as it wishes in the absence of memory barriers. Other replies here go further and suggest that the implementation of the algorithm is also broken without barriers, which is probably true as well.