tags:

views:

86

answers:

2

If there is only one thread to add to queue and only one thread to retrieve from the queue, it is not necessary to lock the queue for those access actions, I think.

Usually the retrieve will be in a loop. If it missed one item, it will get it in next try. only concern is getting a partially data. if it is value type queue and the value is bigger than one basic memory unit, it may happen. but if it is a reference type, it should be ok.

am i right?

+6  A: 

Assuming you are talking about Queue<T>.

As long as the thread which is writing and the thread which is reading are the same thread then no a lock is not needed. If they are different threads then yes indeed a lock is needed. The documentation explicitly states that a lock is needed if there are readers and writers on different threads

JaredPar
If you're using .NET 4 you can use ConcurrentQueue<T> and let that class deal with the synchronisation issues. http://msdn.microsoft.com/en-us/library/dd267265.aspx
Paolo
@Paolo, `ConcurrentQueue<T>` only makes it's own internal data integrity automatic. It, and any other mutable concurrent structure, must be handled with great care. They don't remove race conditions by any means.
JaredPar
A: 

I believe a Queue keeps information in an array; if the number of items in the queue would exceed the size of the array, the array will be replaced with a bigger one. The Queue contains no mechanisms to avoid disrupting queue operations which are in process when such reallocation occurs.

It is certainly possible to construct lock-free queue implementations which will work fine with a concurrent reader and writer. If one uses a linked-list data structure, it is also possible to support multiple concurrent writers without using locks (use Interlocked.CompareExchange to update the queue). A linked-list queue which requires allocating a new object for every insertion will often not be as efficient as an array-based one, but multi-writer queues can be handy.

supercat