While reading Joe Albahari’s excellent book “Threading in C#” I came across the following ambiguous sentence:
A thread-safe type does not necessarily make the program using it thread-safe, and often the work involved in the latter makes the former redundant.
(You can find the sentence on this page; just search for “indeterminacy” to quickly jump to the appropriate section.)
I am looking to use a ConcurrentDictionary to implement certain thread-safe data structures. Is the paragraph telling me that ConcurrentDictionary does not guarantee thread-safe writes to my data structure? Can someone please provide a counter-example that shows a thread-safe type actually failing to provide thread safety?
Thanks in advance for your help.
At the simplest, a thread safe list or dictionary is a good example; having each individual operation thread safe isn’t always enough – for example, “check if the list is empty; if it is, add an item” – even if all thread-safe, you can’t do:
as it could change between the two. You need to synchronize the test and the change.