Thread safe queue

icon3
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...
Posted May 5, 2007 at 18:21 (UTC)

It’s often quite nice to have a blocking queue (thread safe queue) – how many times haven’t you used the producer/consumer-pattern? Because we’re lazy we make one class we can use every time (long live recycling) instead of making that blocking mechanism implicit in out program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Threading;
using System.Collections.Generic;
 
namespace Scienco
{
    class ThreadSafeQueue<T> 
        where T : class
    {
        private Queue<T> mQueue; 
        private Semaphore mSemaphore;
 
        public ThreadSafeQueue()
        {
            mQueue = new Queue<T>();
            mSemaphore = new Semaphore(0, int.MaxValue);
        }
 
        public void Enqueue(T element)
        {
            if (element == null)
            {
                throw new ArgumentNullException();
            }
 
            lock (this.mQueue) 
            {
                this.mQueue.Enqueue(element);
            }
 
            this.mSemaphore.Release();
        }
 
        public T Dequeue()
        {
            this.mSemaphore.WaitOne();
 
            lock (this.mQueue)
            {
                if (this.mQueue.Count > 0)
                {
                    return this.mQueue.Dequeue();
                }
 
                else
                {
                    return null;
                }
            }
        }
    }
}

You probably don’t like my coding-style in some way ({, mQueue or whatever) – please feel free to follow whatever guidelines rocking your world.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.