Shrey Joshi
Shrey Joshi

Reputation: 1206

Locking Variables when Threading in C#

I have a C# program, where I'm spawning a thread to do some calculations. I'm then adding the result of the calculations to a Queue, and from the main thread, I'm constantly checking to see if the Queue has length more than 0. If it does, then the result of the calculation is de-queued and used elsewhere.

I've read that I should lock the queue when accessing it from either thread because it may cause problems if both threads are accessing it at the same time. But should I lock it whenever I do ANYTHING with the Queue, or only when en-queuing/de-queuing?

E.g.

// In main thread

lock (meshDataQueue) {
  if (meshDataQueue.Count > 0)
  {
    constructMesh(meshDataQueue.dequeue())
  }
}

vs.

if (meshDataQueue.Count > 0) {
  lock (meshDataQueue)
  {
    constructMesh(meshDataQueue.dequeue())
  }
}

Upvotes: 2

Views: 270

Answers (1)

Theodor Zoulias
Theodor Zoulias

Reputation: 43941

Yes, you should lock the Queue instance (using always the same "locker" object) whenever you do anything with it, including trivial things like reading the queue's Count. The Queue class is not thread-safe, so for its behavior to stay defined you must ensure that it is accessed by one thread at a time (with proper memory barriers when switching from thread to thread, that the lock statement robustly provides). Otherwise you enter the undefined behavior territory, where all guarantees are off.

Upvotes: 2

Related Questions