# HG changeset patch # User cin # Date 2015-02-18 15:02:02 # Node ID 041b77711262df0d95f4696c420e288e7c8fcea5 # Parent f75cfa58e3d4c2be9d05c597206517df7c6dbb41 fixed blocking queue diff --git a/Implab/Parallels/BlockingQueue.cs b/Implab/Parallels/BlockingQueue.cs --- a/Implab/Parallels/BlockingQueue.cs +++ b/Implab/Parallels/BlockingQueue.cs @@ -23,16 +23,21 @@ namespace Implab.Parallels { public T GetItem(int timeout) { T item; - var t1 = Environment.TickCount; - var dt = timeout; - while (!TryDequeue(out item)) { - lock (m_lock) - if (!Monitor.Wait(m_lock, dt)) - throw new TimeoutException(); - if (timeout >= 0) { - dt = timeout - Environment.TickCount + t1; - if (dt < 0) - throw new TimeoutException(); + + if (!TryDequeue(out item)) { + var t1 = Environment.TickCount; + var dt = timeout; + + lock (m_lock) { + while (!TryDequeue(out item)) { + if (!Monitor.Wait(m_lock, dt)) + throw new TimeoutException(); + if (timeout >= 0) { + dt = timeout - Environment.TickCount + t1; + if (dt < 0) + throw new TimeoutException(); + } + } } } return item; @@ -40,9 +45,11 @@ namespace Implab.Parallels { public T GetItem() { T item; - while (!TryDequeue(out item)) - lock (m_lock) - Monitor.Wait(m_lock); + if (!TryDequeue(out item)) + lock (m_lock) { + while (!TryDequeue(out item)) + Monitor.Wait(m_lock); + } return item; } @@ -51,16 +58,22 @@ namespace Implab.Parallels { var buffer = new T[max]; int actual; - var t1 = Environment.TickCount; - var dt = timeout; - while (!TryDequeueRange(buffer,0,max,out actual)) { - lock (m_lock) - if (!Monitor.Wait(m_lock, dt)) - throw new TimeoutException(); - if (timeout >= 0) { - dt = timeout - Environment.TickCount + t1; - if (dt < 0) - throw new TimeoutException(); + if (!TryDequeueRange(buffer, 0, max, out actual)) { + var t1 = Environment.TickCount; + var dt = timeout; + + lock (m_lock) { + while (!TryDequeueRange(buffer, 0, max, out actual)) { + + if (!Monitor.Wait(m_lock, dt)) + throw new TimeoutException(); + + if (timeout >= 0) { + dt = timeout - Environment.TickCount + t1; + if (dt < 0) + throw new TimeoutException(); + } + } } } @@ -74,9 +87,10 @@ namespace Implab.Parallels { var buffer = new T[max]; int actual; - while (!TryDequeueRange(buffer, 0, max, out actual)) + if (!TryDequeueRange(buffer, 0, max, out actual)) lock (m_lock) - Monitor.Wait(m_lock); + while (!TryDequeueRange(buffer, 0, max, out actual)) + Monitor.Wait(m_lock); var data = new T[actual]; Array.Copy(buffer, data, actual);