0

I'm asking this related to this question: Using events on multithreading socket server

I´ve implemented a ConcurrentQueue thinking it would be needed to avoid problems with multi-threading. When doing it I've noticed the only difference with the standard Queue is in the Dequeue() method, asking for an out parameter.

It made me think the only protection is within the thread(s) dequeuing the object, is this true?

In my game I have a main thread processing my game logic then another thread per player that is doing the jobs of listening, serialising and sending data.

So my ConcurrentQueue will be enqueued and dequeued by different threads but only one and always the same will call either enqueue or dequeue.

So I'm right thinking I'll be OK with a simple queue?

Is ConcurrentQueue only needed when calling Dequeue() simultaneously from multiple threads?

Lloyd
  • 29,197
  • 4
  • 84
  • 98
Nanoc
  • 2,381
  • 1
  • 20
  • 35
  • 2
    In general Queue you need a lock statement (which locks entire queue for a thread) and then you Enqueue/Dequeue. While for ConcurrentQueue you do not need to specifically lock as the to Enqueue/Dequeue would have the necessary item level locks. – Prateek Shrivastava Oct 24 '17 at 09:57
  • "Simple queue" is usually the problem. It is not the queuing that is difficult to do, it is doing something sensible when the queue is empty. ConcurrentQueue takes care of that and avoids having to understand the [mysteries of Monitor.Pulse](https://stackoverflow.com/a/3798033/17034). – Hans Passant Oct 24 '17 at 12:16
  • Needed or advisable? [when-to-use-a-thread-safe-collection](https://learn.microsoft.com/en-us/dotnet/standard/collections/thread-safe/when-to-use-a-thread-safe-collection) – David C Fuchs Nov 09 '18 at 16:45

1 Answers1

4

Im my game i have a main thread processing my game logic then another thread per player that is doing the jobs of listening, serializing and sending data.

So you can end up the situation that at the exact time you dequeue an item, you also enqueue an item in another thread. In that case, the enqueued item might get lost due to the unsafe code in Dequeue (specifically updating class members that can get out of sync). Also, resizing the backing array might cause items to get lost...

You need a ConcurrentQueue.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325