Can dicts be threadsafe?

No one is saying that you will get the wrong result. It’s just that locks in the sense of

is usually not that good of a synchronization strategy (in terms of performance and code maintainability).

With regard to performance, you pay the cost of the lock for any operation and you will also block while waiting for the lock to be released. In the channel case, you can probably go and do other work since putting something into a channel doesn’t necessarily block you.

With regards to code maintainability, for the lock strategy, you need duplicated data structures that just add locks around all the methods. This can be error-prone and toggling between the threaded and unthreaded case can be annoying since you probably want to use the non-locked version of the data structure when you run non-threaded code.

In my opinion, the channel approach is a more composable strategy. You add the synchronization on top of the existing machinery, you don’t modify the machine itself. As a silly example, let’s say people want to put things into a cupboard, but only one person is allowed to put things in there at the same time. You can either have a lock with a single key and everyone fights for the key and tries to put things in there. Or you put a guard outside the cupboard to which everyone leave their things and then go about their other business and it is up to the guard to nicely put things into the cupboard. Putting it like that, it seems likely that the guard can do a better job since he fully controls the insertion process and might e.g. insert things in bulk if possible.

9 Likes