python线程安全可变对象复制 [英] python thread safe mutable object copy
问题描述
是 python的副本
模块线程安全吗?
Is python's copy
module thread safe?
如果没有,我该如何在Python中以线程安全的方式复制Deepcopy可变对象?
If not, how should I copy\deepcopy mutable objects in a thread-safe manner in python?
推荐答案
Python的 GIL 保护字节码,而不是Python语句(请参见 short 或长说明)。由于 copy.copy()
和 copy.deepcopy()
都是在python中实现的,因此它们肯定比单个字节码,所以不,它们不是线程安全的!
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!
如果必须使用多个线程,并且在很多情况下,您应该这样做拥有IO专用线程,则必须做些什么-使用 threading.Lock()
。请注意,您可以对锁定对象使用优雅的with语句。
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.
这篇关于python线程安全可变对象复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!