On Mon, 28 Feb 2022 14:43:36 +0000, Lee Shallis wrote: > Seems the wait just wasn't long enough, at about 4 yields onwards the > results become consistent success, I've attached the file I did the > experiments in, I even tried it under -O3 and no exits were > encountered, so yes my method works, just needs a bit more wait time > for extreme cases Between the lines > if ( !(shared->tid) ) and > shared->tid = tid; the kernel might suspend the running thread and allow the other to run, or you might simply get unlucky and have the two threads do the checks close enough to simultaneously that the memory hasn't been synchronized yet. Either way you end up with both threads seeing that shared->tid is zero and both of them writing their tids to it, and thus both enter the critical section at the same time. And so the lock fails at the very first hurdle: mutual exclusion. No amount of sleeping will make the bug go away, only slightly more difficult to trigger. The point of the clock_nanosleep call was to force a reschedule while holding the lock. This also increases the runtime inside the lock which in this case increases the likelihood that the thread trying to take the lock will be waiting for it and end up racing with the thread that currently has it when it unlocks and tries to relock it. Now that you've inserted lots of sched_yield()s your lock is not only still broken (in more ways than the one we've been trying to get you to understand) but also extremely slow. As a hint for your future education: the first (and far from only) thing you'll need is compare-and-swap, aka. CAS. You can read up on this class of bugs if you'd like. It's called "Time Of Check to Time Of Use" or "TOCTOU" for short. I didn't even need to poke at the code this time as the code you sent breaks just the same on my machine. I hope you'll learn from this.