Making two dictionary writes atomic in multithreaded context
I have two writes to two
ConcurrentDictionary
s, one after the other:
Importantly, they write the same value in two different dictionaries with two different keys, which is important. Problem is that methods read from one dictionary or the other (they don't really utilize both at once) and the sequence of these writes is not atomic, meaning I could get a state where dict1
contains o
but dict2
does not, which is undesirable. Is there any more efficient way to deal with this outside of needing to define a lock for the two of them?6 Replies
First, is it really a problem? If one bit of code is either looking at one dictionary of the other (but not comparing both), there's always going to be a race where that bit of code reads the dictionary just before, or just after, the new element was added
I was thinking a lot if this was a problem at all and I've concluded that it could be, but it's extremely unlikely
It definitely won't corrupt anything, but I could get a weird exception in a weird place
It might be so rare and so insignificant (maybe even impossible in real-world use) that I shouldn't care about this 😄
So, the sort of thing that's guaranteed to occur, then?
I guess
Won't you have the same race if one thread happens to read a dictionary before another thread, but process the value after?
I think you are right