python线程安全的字典,Python的字典中的线程安全

本文讨论了在Python中使用静态方法`addOrder`更新字典类`OrderBook`时,当四个并发线程各自调用该方法时是否需要加锁。作者提醒注意,尽管内置结构在单操作下是线程安全的,但在复杂操作中可能需要确保代码安全。加锁虽然几乎无性能损耗,但提供了代码稳健性保障。
摘要由CSDN通过智能技术生成

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

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)

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

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值