My understanding is, even though we have to use some unsafe code to actually mutate the locked data, the unlock() and lock() methods are still establishing happens-before relationship just fine with Acquire and Store ordering.
And I would expect, data access is to be synchronized correctly. But output says otherwise.
Not sure what am I missing here? Can someone help? Thanks in advance.
... All writes in the current thread are visible in other threads that acquire the same atomic variable.
Your main thread doesn't ever acquire the lock, so writes from the other threads are not guaranteed to be visible to it. Maybe try locking for the final read of that variable?
Your main thread doesn't ever acquire the lock, so writes from the other threads are not guaranteed to be visible to it. Maybe try locking for the final read of that variable?
Good point. I think we don't need lock on the main thread just because, I have used scoped thread here, meaning all the thread will be joined() when scope s ends, which is even before the final assert.
And I believe we always have "happens-before" relationship between the joined thread and what happens after the join call. According to this in the book
Similarly, joining a thread creates a happens-before relationship between the joined thread and what happens after the join() call.
Having said all that. I also tried accessing the data in the final assert with lock() and unlock() Still assertion fails if it runs enough times.
I think the loop condition in lock() is backwards, since swap will return the previous value, it should only exit the loop when swap returns false (the lock was previously unlocked, we locked it), but right now it exits the loop when it returns true.