/** Only one thread should call this at a time */ public T Dequeue(int millisec, out bool timedout) { bool success; T result = _lfq.TryDequeue(out success); bool had_to_wait = !success; if (had_to_wait) { bool cont = true; while (cont) { bool got_set = _are.WaitOne(millisec, false); if (got_set) { result = _lfq.TryDequeue(out success); } /* * If the _are is set, there should be something to * get. If there is not, it is because there was * a race going on with an overlapping Dequeue and Enqueue. * Just try it again in that case. */ bool false_set = got_set && (success == false); cont = false_set; } } timedout = success == false; if (success) { Interlocked.Decrement(ref _count); } return(result); }
public void Run() { object val; bool suc; bool stop = false; do { val = _q.TryDequeue(out suc); if (suc) { Reads++; stop = (val == _stopval); } } while(false == stop); _q.Enqueue(_stopval); }
public void SimpleQueueTest() { LockFreeQueue <object> lfqo = new LockFreeQueue <object>(); LockFreeQueue <int> lfqi = new LockFreeQueue <int>(); Queue q = new Queue(); Random r = _rand; //Put in a bunch of random numbers: int max = r.Next(2048, 4096); for (int i = 0; i < max; i++) { int k = r.Next(); lfqo.Enqueue(k); lfqi.Enqueue(k); q.Enqueue(k); } //Now verify that everything is okay: bool success; int kq; int klfo; int klfi; for (int i = 0; i < max; i++) { klfo = (int)lfqo.TryDequeue(out success); Assert.IsTrue(success, "Dequeue<o> success"); klfi = lfqi.TryDequeue(out success); Assert.IsTrue(success, "Dequeue<i> success"); kq = (int)q.Dequeue(); Assert.AreEqual(kq, klfo, "LockFreeQueue<object> == Queue"); Assert.AreEqual(kq, klfi, "LockFreeQueue<int> == Queue"); } try { lfqi.Dequeue(); Assert.IsTrue(false, "LockFreeQueue<int> post-Dequeue exception"); } catch (InvalidOperationException) { Assert.IsTrue(true, "LockFreeQueue<int> exception"); } try { lfqo.Dequeue(); Assert.IsTrue(false, "LockFreeQueue<object> post-Dequeue exception"); } catch (InvalidOperationException) { Assert.IsTrue(true, "LockFreeQueue<int> exception"); } }
public void Run() { bool success; object next; do { next = _q.TryDequeue(out success); if (success) { if (next != _stop) { Items.Add((object[])next); } } } while(next != _stop); //Put stop back in: _q.Enqueue(_stop); }