Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think I got it... the big hint is "only idle can be done during the initialization phase."</p> <p>First of all, a restriction on mutexes is that you must unlock in the same thread that you locked in. So each <code>unlock()</code> in a thread must be paired with a <code>lock()</code>, and we must have an equal number of them (or else we would get a deadlock).</p> <p>This means that the only way we can prevent a thread from printing multiple times is to ensure that each thread ALWAYS OWNS AT LEAST ONE MUTEX. If thread B at any time released all its mutexes, and then the CPU switched to thread A, it could just run indefinitely.</p> <p>We can't do this with 2 mutexes without deadlock, but we CAN do it with 3.</p> <p>Parent thread:</p> <pre><code> bool initDone = false; lock(m1); lock(m2); spawnChild(); while (!initDone) sleep(); while (true) { print("Parent"); unlock(m1); lock(m3); unlock(m2); lock(m1); unlock(m3); lock(m2); } </code></pre> <p>Child thread:</p> <pre><code> lock(m3); initDone = true; while (true) { lock(m1); unlock(m3); lock(m2); print("Child"); unlock(m1); lock(m3); unlock(m2); } </code></pre> <p>We start with parent owning locks 1 and 2, and child owning 3. Then they take turns releasing and acquiring locks: parent gives lock 1 to child, child gives lock 3 to parent, parent gives lock 2 to child, child gives lock 1 to parent, parent gives lock 3 to child, child gives lock 2 to parent, repeat.</p> <p>An interesting problem; I bet you see the appeal of conditional variables now, as they trivialize this.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload