Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Threading;
- namespace MultithreadingSample
- {
- public sealed class BlockingQueue<T> : IDisposable
- {
- private readonly Queue<T> _queue = new Queue<T>();
- private readonly object _queueLock = new object();
- private readonly SemaphoreSlim _producerSemaphore;
- private readonly SemaphoreSlim _consumerSemaphore;
- public BlockingQueue(int capacity)
- {
- _producerSemaphore = new SemaphoreSlim(capacity, capacity);
- _consumerSemaphore = new SemaphoreSlim(0, capacity);
- }
- public void Dispose()
- {
- _producerSemaphore.Dispose();
- _consumerSemaphore.Dispose();
- }
- public void Enqueue(T obj)
- {
- _producerSemaphore.Wait();
- lock (_queueLock)
- {
- _queue.Enqueue(obj);
- }
- _consumerSemaphore.Release();
- }
- public T Dequeue()
- {
- _consumerSemaphore.Wait();
- T value;
- lock (_queueLock)
- {
- value = _queue.Dequeue();
- }
- _producerSemaphore.Release();
- return value;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement