Python字典中的线程安全

2024-10-04 05:28:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个班有一本字典

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之前必须使用锁?


Tags: namenone字典def线程restaurantclassorders
3条回答

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

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

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

值得注意的是,Google的风格指南建议不要依赖dict原子性,正如我在:Is Python variable assignment atomic?中详细解释的那样

Do not rely on the atomicity of built-in types.

While Python’s built-in data types such as dictionaries appear to have atomic operations, there are corner cases where they aren’t atomic (e.g. if __hash__ or __eq__ are implemented as Python methods) and their atomicity should not be relied upon. Neither should you rely on atomic variable assignment (since this in turn depends on dictionaries).

Use the Queue module's Queue data type as the preferred way to communicate data between threads. Otherwise, use the threading module and its locking primitives. Learn about the proper use of condition variables so you can use threading.Condition instead of using lower-level locks.

我同意这一点:CPython中已经有GIL,因此使用锁的性能影响可以忽略不计。当这些CPython实现细节有朝一日发生变化时,在复杂的代码库中搜索bug所花费的时间要多得多。

是的,内置类型本质上是线程安全的: http://docs.python.org/glossary.html#term-global-interpreter-lock

This simplifies the CPython implementation by making the object model (including critical built-in types such as dict) implicitly safe against concurrent access.

相关问题 更多 >