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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…