in reply to Re^10: Threads sharing global variable
in thread Threads sharing global variable

The unlock-and-block part of cond_wait() is atomic; hence, by the time another thread acquires the lock, this first thread is guaranteed to be in a waiting state.

Spurious signals cannot cause a deadlock either — the test condition is lock-protected and can only proceed when other thread has entered cond_wait() (with the cond variable set to the satisfaction of the first thread).

Replies are listed 'Best First'.
Re^12: Threads sharing global variable
by BrowserUk (Patriarch) on Mar 06, 2016 at 15:08 UTC

      Depending on which thread wins the first lock, the first cond_signal() may be redundant.

      That is: If set_positive() won, it proceeds without waiting, and sends the unnecessary signal. This signal is dropped. But the set_zero() thread can then also proceed without cond_wait(), and subsequently sets the ping-pong going with its own cond_signal().

        It hangs on Windows; and will eventually hang everywhere if you add any useful code to the while loops.

        As a coding pattern, ikegami's code is broken by design. End of.


        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
        In the absence of evidence, opinion is indistinguishable from prejudice.

      Uh. Re: the links you have added. I'm not sure if I follow. The code you posted, is similarly at the mercy of the underlying signaling mechanism.

        The code you posted, is similarly at the mercy of the underlying signaling mechanism.

        My code doesn't hang in its posted form anywhere.

        And add long running code into the processing loops of any or all of the threads and all threads will always be able to make forward progress.

        My code works! As posted, and during evolution to realistic scenarios. By design!


        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
        In the absence of evidence, opinion is indistinguishable from prejudice.