在Python中对线程使用全局字典 [英] Using a global dictionary with threads in Python

查看:986
本文介绍了在Python中对线程使用全局字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

访问/更改字典值是否是线程安全的?

Is accessing/changing dictionary values thread-safe?

我有一个全局词典foo和ID为id1id2,...,idn的多个线程.如果已知每个线程将仅使用其与ID相关的值,比如说id1的线程将仅与foo[id1]一起使用,是否可以访问和更改foo的值而无需为其分配锁,是否可以? /p>

I have a global dictionary foo and multiple threads with ids id1, id2, ... , idn. Is it OK to access and change foo's values without allocating a lock for it if it's known that each thread will only work with its id-related value, say thread with id1 will only work with foo[id1]?

推荐答案

假定CPython:是和否.从多个并发读/写请求不会破坏字典的意义上来说,从共享字典中获取/存储值实际上是安全的.这是由于实现保留了全局解释器锁("GIL").那就是:

Assuming CPython: Yes and no. It is actually safe to fetch/store values from a shared dictionary in the sense that multiple concurrent read/write requests won't corrupt the dictionary. This is due to the global interpreter lock ("GIL") maintained by the implementation. That is:

线程A正在运行:

a = global_dict["foo"]

线程B正在运行:

global_dict["bar"] = "hello"

线程C正在运行:

global_dict["baz"] = "world"

即使所有三个访问尝试均在相同"时间进行,也不会破坏字典.解释器将以某种未定义的方式序列化它们.

won't corrupt the dictionary, even if all three access attempts happen at the "same" time. The interpreter will serialize them in some undefined way.

但是,以下序列的结果是不确定的:

However, the results of the following sequence is undefined:

线程A:

if "foo" not in global_dict:
   global_dict["foo"] = 1

线程B:

global_dict["foo"] = 2

,因为线程A中的测试/设置不是原子的(检查时间/使用时间"竞争条件).因此,通常最好的方法是锁定事物:

as the test/set in thread A is not atomic ("time-of-check/time-of-use" race condition). So, it is generally best, if you lock things:

from threading import RLock

lock = RLock()

def thread_A():
    with lock:
        if "foo" not in global_dict:
            global_dict["foo"] = 1

def thread_B():
    with lock:
        global_dict["foo"] = 2

这篇关于在Python中对线程使用全局字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆