0

I have a .NET queue object. The producer thread do the Enqueue operation, the data enqueued in the queue is a byte[] array, while the other consumer thread do the Dequeue operation on the same queue object.

I use locks to handle concurrency. My code seems to work fine all the time, but yesterday, weird things happened. The data I got from a consumer thread was different from the data I produced: the array length wrong、repeated array... Is this caused by the failed thread-safe protection?

In my opinion, concurrency would only cause data loss.

My first post here, bear with me.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sunf71
  • 93
  • 2
  • 8
  • 2
    Can you tell us what mechanism you use to lock? e.g. with a VERY short code sample. – Binary Worrier Jan 14 '10 at 11:15
  • Concurrency issues causes data corruption or inconsistency. It could be data loss, repeated data, corrupt data, or even an exception. What happens depends on your implementation. Without seeing an example of what you are doing, no one can have any idea what your problem is. – shf301 Jan 14 '10 at 12:45
  • thanks for your comments! i simply use monitor to do the "lock" get { Monitor.Enter(mQueue); byte[] data = mQueue.Dequeue(); Monitor.Exit(mQueue); return data; } set { Monitor.Enter(mQueue); mQueue.Enqueue(value); Monitor.Exit(mQueue); } what's wrong with this? – Sunf71 Jan 17 '10 at 06:28

2 Answers2

0

The producer thread should not keep a reference to the array and modify it after it's enqueued. Always create a new array. (I may be stating the obvious, but it's hard to do better without more information)

Henrik
  • 23,186
  • 6
  • 42
  • 92
0

It is far worse than simple data loss. The Queue class can re-allocate its internal buffer when needed to accommodate a growing number of elements. Improper locking can access the new buffer with old values of the head and tail indices. You'll only get an exception when you're lucky, more likely is that you simply get the wrong element.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536