Re:A spin lock in C that does not require a machine level ex...
by jacquesm on Sunday May 04, 2014 @08:36PM
(#7696466)
Yes, task switches unfortunately do not happen at the level of 'C' code but between machine instructions!
Run your compiler -S and save the output, then try to reason through the consequences of a context switch in between every instruction with multiple threads contending for the lock. And have a look at the manual for your CPU to learn about out-of-order execution and cache coherency between multiple cores / cpus.
Some interesting reading on the subject:
https://www.kernel.org/doc/Documentation/memory-barriers.txt
If you want to do this entirely in userspace and you must avoid atomic instructions for some reason consider abstracting out your locking to a separate process and use IPC, first come first serve.
if thread 1 is pre-empted by thread 2 and thread 2 is able to get to the same point (line 33) then G1 will be equal to 2. both threads will assign G2 = 2 and thread 2 will win the race -- thread 1 will loop and begin to spin again.
have i missed something?