|
Shareability
Which objects can be shared between threads
You probably know how to append to a list or modify a dict. When confronted with threading though you may start to wonder, what happens if two threads modify a list or a dict simultaneously? There's two common answers to this:
My priority is making it easy to write correct programs, and neither of those options are good enough. Instead, I take a third option as my default:
Of course if you couldn't share any objects then you'd just have processes, which are quite awkward to use. Instead, I only make mutable objects like list and dict unshareable, while immutable int and str objects can still be shared. Further, mutable objects that provide an explicit API for use between threads are also shareable. A Monitor is a major example of the latter. It lets you store unshareable objects safely inside, while the Monitor itself is shareable and passed between threads. Another example is a shareddict. It's a dict that can only have shareable keys and values, and all the operations are atomic. It's used for module and class dictionaries, which typically aren't modified after startup. |