Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to iterate over an unchanging dictionary from multiple threads?

I've got code like this that's executed from many threads simultaneously (over shared a and b objects of type Dictionary<int, double>):

foreach (var key in a.Keys.Union(b.Keys)) {
    dist += Math.Pow(b[key] - a[key], 2);
}    

The dictionaries don't change during the lifetime of the threads. Is this safe? So far, it seems OK, but I wanted to be sure.

like image 882
Cameron Avatar asked Dec 10 '11 02:12

Cameron


People also ask

Are dictionaries in python thread-safe?

Many common operations on a dict are atomic, meaning that they are thread-safe.

Is reading a dictionary thread-safe?

Yes, reading a Dictionary concurrently is a perfectly valid operation. According to the thread safety section of the documentation, A Dictionary<TKey,TValue> can support multiple readers concurrently, as long as the collection is not modified.

Are Python maps thread-safe?

Python's built-in structures are thread-safe for single operations, but it can sometimes be hard to see where a statement really becomes multiple operations. Your code should be safe.

Is dictionary in Swift thread-safe?

Dictionaries in Swift are not thread safe , they lead to wierd crashes which are very hard to debug. This class solves this problem by using a dictionary whose accesses are made thread safe by using a concurrent queue with a barrier.


1 Answers

From the dictionary documentation:

A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

As long as you're never writing, it should be safe.

like image 150
Reed Copsey Avatar answered Sep 28 '22 02:09

Reed Copsey