Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is my solution after some experimentation:</p> <ul> <li>If the single-element queue is empty, we take the spot.</li> <li>If the spot is already taken, we politely nudge the occupant to move on, wait a bit and try again.</li> <li>If someone is rude and hijacks the spot while we're waiting, we jump the queue and move on.</li> </ul> <p><em>Code:</em></p> <pre><code>Message WrapA(int a, int millisecondsTimeout) { bool lockTaken = false; int? b = null; try { Monitor.TryEnter(gate, millisecondsTimeout, ref lockTaken); if (lockTaken) { if (pendingB != null) { b = pendingB; pendingB = null; Monitor.Pulse(gate); } } } finally { if (lockTaken) { Monitor.Exit(gate); } } return new Message(a, b); } Message WrapB(int b, int millisecondsTimeout) { bool lockTaken = false; try { TimeoutHelper timeout = new TimeoutHelper(millisecondsTimeout); Monitor.TryEnter(gate, timeout.RemainingTime(), ref lockTaken); if (lockTaken) { if (pendingB == null) { pendingB = b; Monitor.Wait(gate, timeout.RemainingTime()); if (pendingB == null) return null; pendingB = null; } else { Monitor.Pulse(gate); try { } finally { lockTaken = false; Monitor.Exit(gate); } Thread.Sleep(1); Monitor.TryEnter(gate, timeout.RemainingTime(), ref lockTaken); if (lockTaken) { if (pendingB == null) { pendingB = b; Monitor.Wait(gate, timeout.RemainingTime()); if (pendingB == null) return null; pendingB = null; } } } } } finally { if (lockTaken) { Monitor.Exit(gate); } } return new Message(null, b); } </code></pre>
 

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