Python的字典中的线程安全 [英] Thread Safety in Python's dictionary

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

问题描述

我有一个持有字典的课程

I have a class which holds a dictionary

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 。这是每个线程运行的函数:

And I am running 4 threads (one for each restaurant) that call the method OrderBook.addOrder. Here is the function ran by each thread:

def addOrders(restaurant_name):

    #creates orders
    ...

    OrderBook.addOrder(restaurant_name, orders)

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

Is this safe, or do I have to use a lock before calling addOrder?

推荐答案

Python的内置结构对于单个操作是线程安全的,但有时候很难看到语句真正成为多个操作。

Python's built-in structures are thread-safe for single operations, but it can sometimes be hard to see where a statement really becomes multiple operations.

你的代码应该是安全的请记住:这里的锁几乎不会增加开销,并且会让您放心。

Your code should be safe. Keep in mind: a lock here will add almost no overhead, and will give you peace of mind.

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

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

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