Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi threading on dictionary with fixed keys

I have a dictionary with a fixed collection of keys, which I create at the beginning of the program. Later, I have some threads updating the dictionary with values.

  • No pairs are added or removed once the threads started.
  • Each thread has its own key. meaning, only one thread will access a certain key.
  • the thread might update the value.

The question is, should I lock the dictionary?

UPDATE:

Thanks all for the answers,

I tried to simplify the situation when i asked this question, just to understand the behaviour of the dictionary.

To make myself clear, here is the full version: I have a dictionary with ~3000 entries (fixed keys), and I have more than one thread accessing the key (shared resourse), but I know for a fact that only one thread is accessing a key entry at a time.

so, should I lock the dictionary? and - when you have the full version now, is a dictionary the right choise at all?

Thanks!

like image 517
Keren Avatar asked Oct 15 '13 09:10

Keren


Video Answer


2 Answers

FROM MSDN

A Dictionary can support multiple readers concurrently, as long as the collection is not modified.

To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

For a thread-safe alternative, see ConcurrentDictionary<TKey, TValue>.

like image 168
Rajesh Subramanian Avatar answered Oct 03 '22 15:10

Rajesh Subramanian


Let's deal with your question one interpretation at a time.

First interpretation: Given how Dictionary<TKey, TValue> is implemented, with the context I've given, do I need to lock the dictionary?

No, you don't.

Second interpretation: Given how Dictionary<TKey, TValue is documented, with the context I've given, do I need to lock the dictionary?

Yes, you definitely should.

There is no guarantee that the access, which might be OK today, will be OK tomorrow, in a multithreaded world since the type is documented as not threadsafe. This allows the programmers to make certain assumptions about the state and integrity of the type that they would otherwise have to build in guarantees for.

A hotfix or update to .NET, or a whole new version, might change the implementation and make it break and this is your fault for relying on undocumented behavior.

Third interpretation: Given the context I've given, is a dictionary the right choice?

No it isn't. Either switch to a threadsafe type, or simply don't use a dictionary at all. Why not just use a variable per thread instead?

Conclusion: If you intend to use the dictionary, lock the dictionary. If it's OK to switch to something else, do it.

like image 28
Lasse V. Karlsen Avatar answered Oct 03 '22 15:10

Lasse V. Karlsen