我有一个班有一本字典
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的内置结构对于单个操作是线程安全的,但是有时很难看出一个语句真正变成了多个操作。
你的代码应该是安全的。记住:这里的锁几乎不会增加开销,而且会让你安心。
http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm有更多详细信息。
值得注意的是,Google的风格指南建议不要依赖dict原子性,正如我在:Is Python variable assignment atomic?中详细解释的那样
我同意这一点:CPython中已经有GIL,因此使用锁的性能影响可以忽略不计。当这些CPython实现细节有朝一日发生变化时,在复杂的代码库中搜索bug所花费的时间要多得多。
是的,内置类型本质上是线程安全的: http://docs.python.org/glossary.html#term-global-interpreter-lock
相关问题 更多 >
编程相关推荐