Created
October 29, 2013 05:09
-
-
Save jakesays-old/7209414 to your computer and use it in GitHub Desktop.
SuperQueue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
} | |
// Define other methods and classes here | |
public class SuperQueue<TElement> | |
{ | |
private Queue<TElement> _queue1 = new Queue<TElement>(); | |
private Queue<TElement> _queue2 = new Queue<TElement>(); | |
private ReaderWriterLockSlim _producerGuard = new ReaderWriterLockSlim(); | |
private Queue<TElement> _producerQueue = _queue1; | |
public void Enqueue(TElement item) | |
{ | |
try | |
{ | |
_producerGuard.EnterReadLock(); | |
_producerQueue.Enqueue(item); | |
} | |
finally | |
{ | |
_producerGuard.ExitReadLock(); | |
} | |
} | |
public void Consume(Action<TElement> consumer) | |
{ | |
Queue<TElement> currentQueue = null; | |
try | |
{ | |
_producerGuard.EnterWriteLock(); | |
currentQueue = _producerQueue; | |
if (currentQueue == _queue1) | |
{ | |
_producerQueue = _queue2; | |
} | |
else | |
{ | |
_producerQueue = _queue1; | |
} | |
} | |
finally | |
{ | |
_producerGuard.ExitWriteLock(); | |
} | |
while (currentQueue.Count > 0) | |
{ | |
consumer(currentQueue.Dequeue()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment