Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python thread safe mutable object copy

Is python's copy module thread safe?

If not, how should I copy\deepcopy mutable objects in a thread-safe manner in python?

like image 950
Jonathan Livni Avatar asked Jun 26 '13 14:06

Jonathan Livni


1 Answers

Python's GIL protects bytecodes, not Python statements (see short or long explanations). As both copy.copy() and copy.deepcopy() are implemented in python, they are certainly more than a single bytecode, so no, they are not thread safe!

If you must work with multiple threads, and there are many cases you should such as having IO dedicated threads, do what must be done - use threading.Lock(). Notice you can use the elegant with statement with the lock object.

like image 122
Jonathan Livni Avatar answered Oct 09 '22 11:10

Jonathan Livni