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.
Many common operations on a dict are atomic, meaning that they are 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With