您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python内置容器是线程安全的吗?

Python内置容器是线程安全的吗?

您需要为将在Python中修改的所有共享变量实现自己的锁定。你不必担心从不会被修改的变量读(即并发读取都OK了),所以稳定的类型(frozensettuplestr)都可能是 安全的,但它不会伤害。对于你将要改变的东西- ,listsetdict和大多数其他的对象,你应该有自己的锁定机制(而就地操作都OK在大多数的这些,线程可以导致超级讨厌的错误- 你还不如很好地实现锁定,这非常容易)。

顺便说一句,我不知道您是否知道,但是锁定在Python中非常容易-创建一个threading.lock对象,然后您可以像这样获取/释放它:

import threading
list1Lock = threading.Lock()

with list1Lock:
    # change or read from the list here
# continue doing other stuff (the lock is released when you leave the with block)

在Python 2.5中,执行from __future__ import with_statement; Python 2.4及更低版本没有此功能,因此您需要将acquire()/ release()调用放在try:...finally:块中:

import threading
list1Lock = threading.Lock()

try:
    list1Lock.acquire()
    # change or read from the list here
finally:
    list1Lock.release()
# continue doing other stuff (the lock is released when you leave the with block)

关于Python中线程同步的一些非常好的信息

python 2022/1/1 18:41:40 有279人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶