python - Python字典中的线程安全

标签 python multithreading dictionary thread-safety

我有一个包含字典的类

class OrderBook:
    orders = {'Restaurant1': None,
              'Restaurant2': None,
              'Restaurant3': None,
              'Restaurant4': None}

    @staticmethod
    def addOrder(restaurant_name, orders):
        OrderBook.orders[restaurant_name] = orders

我正在运行 4 个线程(每个餐厅一个)调用方法 OrderBook.addOrder。这是每个线程运行的函数:

def addOrders(restaurant_name):

    #creates orders
    ...

    OrderBook.addOrder(restaurant_name, orders)

这样安全吗,还是我必须在调用 addOrder 之前使用锁?

最佳答案

Python 的内置结构对于单个操作是线程安全的,但有时很难看出一条语句在哪里真正变成了多个操作。

您的代码应该是安全的。请记住:这里的锁几乎不会增加任何开销,并且会让您高枕无忧。

https://web.archive.org/web/20201108091210/http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm有更多细节。

关于python - Python字典中的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6953351/

相关文章:

javascript - Angular 中如何实现多线程?

swift - 如何在 swift 中向字典添加新键?

python - 如何将样条曲线拟合转换为分段函数?

python - Unicode解码错误: 'utf8' codec can't decode byte 0xcb in position 5: invalid continuation byte

python - 惰性评估 : forward operations to deferred value

java - 如何通知正在运行的线程发生更改

python - 如何使用 apache2 和 mod_wsgi 获取 Django 调试页面

python - python中的调用堆栈是否分别在多线程和多处理中的线程或进程之间共享?

python - 使用映射字典更改字典的键

linux - 预设字典是否仅对前 32 K 字节的数据有用?