Search code examples
c#network-programmingthread-safetyvolatile

Is the use of a volatile dictionary a good option when high speed network messaging is involved?


Premise

I am working on a multiplayer game and I have a number of network controlled actors, the inputs of witch I decided to store in a volatile dictionary:

public static volatile Dictionary<string, QuickMessage> quickPlayerMessages;

And each frame the actors fetch their values from that dictionary, but independently of that I also have a receiver thread that constantly updates that dictionary, so the values constantly get changed and keys may be deleted or added to it. I did a few tests and this works but...

My concerns

I do not fully understand the volatile modifier, I know that it is supposed to eliminate some optimizations that may result in the reading of a partially written information. I also heard that this isn't really functioning like if you did it with a lock mechanism. While I did pick this solution because it cut down a lot of complexity for me and it looks like it is fairly responsive(speedwise) I do have this feeling of unease about it.

Is there any issue that may arise or that I should be aware of from this approach?


Solution

  • volatile is probably not the correct approach for this. What volatile does is forcing the value to be read from memory rather than from cache. Reading or writing a reference, or a value smaller than a IntPtr is atomic in c#. But without some kind of memory barrier the value could be cached, and changes on one thread might not be visible for other threads. Volatile inserts some memory barriers to solve some of the visibility issues.

    In this scenario you do not seem to replace the dictionary, so volatile would do nothing. You are however mentioning you are updating the dictionary. This is not threadsafe without a lock. But you might however consider a ConcurrentDictionary<TKey, TValue> instead. A concurrent dictionary would however only guarantee that the dictionary itself is thread safe, you will still need to consider the overall thread safety of your program.

    Also, your primary concern should be that the program is correct, speed is secondary.