列表是线程安全的吗? [英] Are lists thread-safe?

查看:82
本文介绍了列表是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到通常建议使用具有多个线程的队列,而不是列表和.pop().这是因为列表不是线程安全的,还是出于其他原因?

I notice that it is often suggested to use queues with multiple threads, instead of lists and .pop(). Is this because lists are not thread-safe, or for some other reason?

推荐答案

列表本身是线程安全的.在CPython中,GIL可以防止对它们的并发访问,并且其他实现请谨慎使用细粒度锁或同步数据类型作为其列表实现.但是,虽然列表本身不会因尝试并发访问而损坏,但是列表的 data 不受保护.例如:

Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:

L[0] += 1

如果另一个线程做同样的事情,则不能保证

实际上将L [0]加1,因为+=不是原子操作. (实际上,Python中很少有原子操作的操作,因为大多数操作都会导致调用任意Python代码.)您应该使用Queues,因为如果您仅使用不受保护的列表,则可能会获得或删除错误的项. 由于种族条件.

is not guaranteed to actually increase L[0] by one if another thread does the same thing, because += is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.

这篇关于列表是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆