Python 字典中的线程安全 [英] Thread Safety in Python's dictionary
本文介绍了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
.这是每个线程运行的函数:
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.
这篇关于Python 字典中的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文