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 f开发者_运维百科rom 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.
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.
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)
精彩评论