5YrsLaterDBA
5YrsLaterDBA

Reputation: 34770

do we need to lock this queue?

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?

Upvotes: 2

Views: 747

Answers (2)

supercat
supercat

Reputation: 81179

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.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754803

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

Upvotes: 6

Related Questions