3

I have a Queue<T> field that is accessed by various threads. Enequeue() is called from multiple threads many times per second, while there is a single thread that performs the Dequeue() and Count operations.

I havent been thinking much about this until now, since I played it "safe" and used lock on a static object before any operations with this queue. While there currently aren't any performance issue, I would like to get rid of the locks if they are redundant. My questions are:

  1. since I never iterate through the queue, are locks really needed in this situation? I mean, will the program crash when it happens that one thread enqueues and the second thread dequeues elements at exactly the same time?
  2. should I perhaps use Queue.Synchronized() to get a wrapper, and if so: will that impact performance compared to the original queue?
avance70
  • 787
  • 1
  • 11
  • 22

1 Answers1

3

1: yes they are necessary; both enqueue and dequeue mutate state; a standard queue is not thread safe

2: ConcurrentQueue<T> would work nicely; personally I use a version I wrote here on SO, Creating a blocking Queue<T> in .NET? - it makes it easy to throttle the size of the queue, and do efficient dequeues without looping

Note; with your current implementation the lock-object should only be static if the queue is static (that isn't clear in the question, though) - otherwise all your similar queues may be sharing a lock

Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thanks, `ConcurrentQueue` appears to be working all the job for me, without the heavy locks. – avance70 Apr 26 '11 at 12:53
  • @avance70 - unless you've profiled, I wouldn't automatically assume that the locks are "heavy" here... – Marc Gravell Apr 26 '11 at 13:09
  • I think my locks were pretty nicely implemented, affecting really only a few necessary rows. But, as you suggested `ConcurrentQueue` I read somewhere that it uses `System.Threading.Interlocked` operations which are less expensive than the `lock` – avance70 Apr 26 '11 at 13:21