python thread safe mutable object copy

2019-06-24 11:37发布

Is python's copy module thread safe?

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

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-06-24 12:20

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.

查看更多
登录 后发表回答