Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.28 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4.  
  5. namespace MultithreadingSample
  6. {
  7.     public sealed class BlockingQueue<T> : IDisposable
  8.     {
  9.         private readonly Queue<T> _queue = new Queue<T>();
  10.         private readonly object _queueLock = new object();
  11.         private readonly SemaphoreSlim _producerSemaphore;
  12.         private readonly SemaphoreSlim _consumerSemaphore;
  13.  
  14.         public BlockingQueue(int capacity)
  15.         {
  16.             _producerSemaphore = new SemaphoreSlim(capacity, capacity);
  17.             _consumerSemaphore = new SemaphoreSlim(0, capacity);
  18.         }
  19.  
  20.         public void Dispose()
  21.         {
  22.             _producerSemaphore.Dispose();
  23.             _consumerSemaphore.Dispose();
  24.         }
  25.  
  26.         public void Enqueue(T obj)
  27.         {
  28.             _producerSemaphore.Wait();
  29.  
  30.             lock (_queueLock)
  31.             {
  32.                 _queue.Enqueue(obj);
  33.             }
  34.  
  35.             _consumerSemaphore.Release();
  36.         }
  37.  
  38.         public T Dequeue()
  39.         {
  40.             _consumerSemaphore.Wait();
  41.  
  42.             T value;
  43.  
  44.             lock (_queueLock)
  45.             {
  46.                 value = _queue.Dequeue();
  47.             }
  48.  
  49.             _producerSemaphore.Release();
  50.             return value;
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement