是列表.poppython中的线程安全

2024-04-28 14:56:18 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个用随机值初始化列表的程序。然后应用程序生成一组线程,每个线程不断地从这个共享列表中弹出项目。我的问题是,这个操作是否线程安全:

try:
    while global_list.pop():
        ...do something ..
except:
    print ("list is empty")

是否会因为线程之间的竞争条件而丢失数据

编辑:我已经提到了链接Are lists thread-safe,但是在引用的问题中有对列表数据的操作,我只是说从列表中弹出项目,这是在修改列表,而不是其中的数据。在我的代码片段dosomething并不表示对列表数据的操作,它只是一些与列表数据无关的处理。在


Tags: 数据项目程序应用程序列表线程popglobal
1条回答
网友
1楼 · 发布于 2024-04-28 14:56:18

我的答案是-从全局列表中取出元素(pop),它一次被多个线程使用,是线程安全的

原因是因为它是原子操作。在

一次一个操作就是原子操作。

检查这个link。在

来自上面的链接

An operation acting on shared memory is atomic if it completes in a single step relative to other threads. When an atomic store is performed on a shared variable, no other thread can observe the modification half-complete. When an atomic load is performed on a shared variable, it reads the entire value as it appeared at a single moment in time. Non-atomic loads and stores do not make those guarantees.

对列表的任何操作都不是原子操作,所以需要特别注意使用锁、事件、条件或信号量等使其线程安全。 这在Are lists thread-safe中解释。在

相关问题 更多 >