in reply to Re^12: Threads sharing global variable (disingenous)
in thread Threads sharing global variable
One must sit in cond_wait() while the other is working.
Why? That's complete nonsense.
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.
The most basic principle of locking is that you hold lock for a short a period as possible. Ie. They should only attempt to acquire the lock immediately before they are ready to modify the shared resource.
That's Locking & Syncing 101. That way, if the other thread isn't holding the lock, the attempt to acquire it succeeds immediately, and they can get straight on to making the modification and releasing the lock.
With luck, the other thread was busy with its other stuff for the entire time and was neither affected (slowed down) by the action of the first thread, nor imposed any delay upon the first thread.
Ditto vice versa. When the second thread wants to make its change, if the first thread isn't holding the lock, then it can get straight on with its change, without ever affecting or being affected by the other thread.
And that's the Holy Grail of resource sharing; free running (non-blocking) shared resource access for both (all) threads most if the time, with blocking only occurring: a) occasionally; b) for very short periods; when the dynamic periodicities of the threads happen to coincide.
What you are suggesting -- is what Ikegami's code does -- is to make it so that only one thread can ever be doing *anything* at any given time. And that stupid. You -- quite literally -- would be better off using a single thread and just interleaving the code from the two threads.
It would achieve the same processing, with better performance; and the added bonus that you'd be guaranteed not to create deadlocks.
Which makes what you are suggesting -- and what Ikegami implemented -- broken. By design!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^14: Threads sharing global variable (disingenous)
by Anonymous Monk on Mar 09, 2016 at 21:03 UTC | |
by BrowserUk (Patriarch) on Mar 09, 2016 at 21:22 UTC | |
by Anonymous Monk on Mar 09, 2016 at 22:30 UTC | |
by BrowserUk (Patriarch) on Mar 09, 2016 at 22:55 UTC |