Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queue<T> thread-safety: one writer, one reader

I've got a Queue<T> _q = new Queue<T>();

There's always only one thread populating it: _q.Enqueue(msg);

There's always only one thread consuming it: _q.Dequeue();

I want to be lock-free in both threads. Performance is important but safety is on the first place.

Do I need making _q a ConcurrentQueue<T>?

UPD That can be important: I do not need to be sure that reading thread will successfully dequeue item immediatly after writing thread enqueues it. If a few false dequeues will be taken - that's ok.

like image 951
astef Avatar asked Mar 23 '23 08:03

astef


2 Answers

Do I need making _q a ConcurrentQueue

Yes. A Queue is not thread safe.

like image 142
nos Avatar answered Mar 31 '23 21:03

nos


Here you can find a lock free queue: Lockfreie threadsichere Queue - don't be afraid of the site being in german - the code should speak for itself. Furthermore, there's another, little more in-depth article at Writing Lock-Free Code: A Corrected Queue

like image 37
JeffRSon Avatar answered Mar 31 '23 19:03

JeffRSon