The msdn documentation states that a static generic Queue is thread-safe. Does this mean that the following code is thread-safe? In other words, is there a problem when a thread Enqueues an int and another thread Dequeues an int at the same time? Do I have to lock the Enqueue and Dequeue operations for thread-safety?
class Test {
public static Queue<int> queue = new Queue<int>(10000);
Thread putIntThread;
Thread takeIntThread;
public Test() {
for(int i = 0; i < 5000; ++i) {
queue.Enqueue(0);
}
putIntThread = new Thread(this.PutInt);
takeIntThread = new Thread(this.TakeInt);
putIntThread.Start();
takeIntThread.Start();
}
void PutInt() {
while(true)
{
if(queue.Count < 10000) {//no need to lock here as only itself can change this condition
queue.Enqueue(0);
}
}
}
void TakeInt() {
while(true) {
if(queue.Count > 0) {//no need to lock here as only itself can change this condition
queue.Dequeue();
}
}
}
}
Edit: I have to use .NET 3.5
This is absolutely not thread-safe. From the docs of
Queue<T>.Rereading your question, you seem to be confused about the phrase "static members of this type" – it’s not talking about "a static Queue" as there’s no such thing. An object isn’t static or not – a member is. When it talks about static members it’s talking about things like
Encoding.GetEncoding(Queue<T>doesn’t actually have any static members). Instance members are things likeEnqueueandDequeue– members which relate to an instance of the type rather than the type itself.So either you need to use a lock for each action, or if you’re using .NET 4, use
ConcurrentQueue<T>.