C
C#•3y ago
LPeter1997

Making two dictionary writes atomic in multithreaded context

I have two writes to two ConcurrentDictionarys, one after the other:
dict1[k1] = o;
dict2[k2] = o;
dict1[k1] = o;
dict2[k2] = o;
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
canton7
canton7•3y ago
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
LPeter1997
LPeter1997OP•3y ago
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 😄
canton7
canton7•3y ago
So, the sort of thing that's guaranteed to occur, then?
LPeter1997
LPeter1997OP•3y ago
I guess
canton7
canton7•3y ago
Won't you have the same race if one thread happens to read a dictionary before another thread, but process the value after?
LPeter1997
LPeter1997OP•3y ago
I think you are right
Want results from more Discord servers?
Add your server