So in a nutshell you are claiming that: two threads can, in fact, both acquire and simultaneously hold a lock on a shared variable?
NO! How on earth can you misread what I wrote so grossly?
I wrote: "Both threads can be neither holding the lock, nor waiting for a lock; they can just be doing stuff that doesn't involve using the shared resource."
Sorry if English is not your first language, but those two statements are completely (and unmistakably) different; unrelated; Almost, but not quite polar opposites.
Do you agree, that two threads, that have no need for access to a shared resource, can both run concurrently. (I'm gonna assume that you do, because anything else would be ridiculous.)
Therefore, it is a simple step to envisage two threads that each have lots of stuff to do; that each occasionally need to access the same resource -- say a shared variable -- running concurrently without any locks in place.
Now most of the time neither of them hold any locks. They just go about their business, each essentially completely ignorant of the other threads existence.
And then, when either one of them needs access to the shared variable, it acquires the lock, makes its change and releases it again. And most of the time, the other thread will still be totally unaware of the first threads existence.
And when the second thread needs to access the shared variable, it does exactly the same thing: acquires the lock; makes its change; and releases the lock. And the first thread need never be aware of any of it.
Occasionally, they will both attempt to acquire the lock at (roughly) the same time. One will succeed, and the other will block -- at the lock() -- when the one that succeeded finishes, it simply releases the lock. It doesn't even need to signal or broadcast.
When the winner releases the lock, the other thread's lock() succeeds and returns, it makes its change, and releases. All done.
No possibility for deadlocks; no possibility for missed signals; no unnecessary contention; and no lock-stepping of threads.
In reply to Re^15: Threads sharing global variable (disingenous)
by BrowserUk
in thread Threads sharing global variable
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |