how do you share an object with threads in python? - such as a lists or dictionaries.
-
not too sure why this question has been marked down. there seems to be nothing similar to multiprocessing.Manager for threads that i can see online? – AndrewE Oct 03 '20 at 13:12
-
I think your question is very vague. Could you make it more specific by describing a situation where you need multiple threads to share an object? Depending on the requirements of a particular situation, there may be specific protections needed against race conditions/concurrency. – Patrick Oct 03 '20 at 13:32
-
_“there seems to be nothing similar to multiprocessing.Manager for threads”_ — That should’ve been included in your question. Your question shows no attempts of your own. – Sebastian Simon Oct 03 '20 at 13:44
1 Answers
Threads share the same process space so the object that one thread sees is the same object another thread sees. The real question of sharability comes down to whether the operations you are performing on these objects are "thread safe". When you are executing Python code, the interpreter obtains the Global Interpreter Lock and no two threads can be executing Python byte code in parallel. But you could write code consisting of many Python statements that manipulate a data structure. If this code is running against the same data structure (object) concurrently in multiple threads, you could end up with a data structure that is corrupted since there is the possibility of a thread giving up control to the other thread in mid-computation. In this case you need to use locking to prevent this. On the other hand, if you have a built-in type, such as a list
, and you do an append
operation, that would be thread safe without your doing any explicit locking.

- 38,656
- 3
- 37
- 60