python多线程操作字典_关于多线程:Python字典中的线程安全

我有一个持有字典的班级

1

2

3

4

5

6

7

8

9class OrderBook:

orders = {'Restaurant1': None,

'Restaurant2': None,

'Restaurant3': None,

'Restaurant4': None}

@staticmethod

def addOrder(restaurant_name, orders):

OrderBook.orders[restaurant_name] = orders

我正在运行调用方法OrderBook.addOrder的4个线程(每个餐厅一个)。 这是每个线程运行的函数:

1

2

3

4

5

6def addOrders(restaurant_name):

#creates orders

...

OrderBook.addOrder(restaurant_name, orders)

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

无论如何,当每个线程写入不同的密钥时,怎么会出现问题。

@Jochen:取决于如何实现dicts,很多可能会出错。 这是一个非常合理的问题。

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

您的代码应该是安全的。请记住:这里的锁定几乎不会增加任何开销,让您高枕无忧。

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

下面是effbot.org实现锁定的原因/方法

应该考虑单个操作与复合操作,例如get-add-set。

问题是,当我经常读/写那个词时,那种安心会让我付出很多代价。

是的,内置类型本质上是线程安全的:

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.

这不是Python的功能,而是cpython的功能。

没错,但据我所知,Jython和IronPython中的内置函数也是线程安全的,即使没有使用GIL(和unladen swallow,如果它出现,也建议取消GIL)。 我认为既然他没有指定他正在使用的翻译,那他就是CPython的意思。

在Jython的情况下更正:jython.org/jythonbook/en/1.0/

值得注意的是,谷歌的风格指南建议不要依赖于dict原子性,正如我在下面进一步详细解释的那样:Python变量赋值是原子的吗?

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,因此使用Lock的性能可以忽略不计。当CPython实现细节有一天发生变化时,复杂代码库中花费的时间会花费更多的成本。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值