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

标签 python thread-safety

我想知道 Python 内置容器(list、vector、set...)是否是线程安全的?还是我需要为我的共享变量实现锁定/解锁环境?

最佳答案

您需要为所有将在 Python 中修改的共享变量实现自己的锁定。你不必担心从不会被修改的变量中读取(即并发读取是可以的),所以不可变类型(frozensettuplestr) 是可能安全的,但它不会受到伤害。对于您将要更改的内容 - listsetdict 和大多数其他对象,您应该有自己的锁定机制(虽然在大多数情况下就地操作都可以,但线程可能会导致非常讨厌的错误 - 你不妨实现锁定,这很容易)。

顺便说一句,我不知道你是否知道,但是在 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: blocks:

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)

Some very good information about thread synchronization in Python .

关于python - Python 内置容器是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2227169/

相关文章:

python - 从 Splash 请求中读取 cookie

python - 是否有适用于 Windows 的 Python PDF 元数据编写库?

java - 在java中实现同步addAll到列表

jpa - 有没有办法改变方法的JPA提取类型?

python - 这是 notnull() 的 Pandas 错误还是我的根本误解(可能是误解)

python - 如何自动将one2many字段值填充到odoo中的另一个one2many字段

python - 使用 App Engine oauth 服务

python - 如何确保与 uWSGI 和 Pyramid 的唯一 SQLAlchemy 数据库连接

multithreading - 不变的数据结构如何不是线程安全的?

python - Flask 中的全局变量是线程安全的吗?如何在请求之间共享数据?