joh*_*ith 5 python multithreading
lets say I have a program which initializes a list with random values. The application then spawns a bunch of threads and each thread keeps popping items out of this shared list. My question is , is this operation thread safe :
try:
while global_list.pop():
...do something ..
except:
print ("list is empty")
Run Code Online (Sandbox Code Playgroud)
Will it ever be the case that data is lost due to race condition between threads
EDIT: I have referred to link Are lists thread-safe , however there is manipulation on list data in the referenced question, I am simply talking about popping items out of list which is modifying the list and not the data within. In my code snippet do something does not signify operations on list data, it is simply some processing unrelated to list data.
我的答案是肯定的-要获取一次由多个线程使用的全局列表的元素(弹出),是线程安全的
原因是因为它是原子操作。
一次一个操作是原子操作。
检查此链接。
从上面的链接
如果作用于共享内存的操作相对于其他线程在单个步骤中完成,则该操作是原子的。当对共享变量执行原子存储时,没有其他线程可以观察到半完成的修改。当对共享变量执行原子加载时,它会读取单个时刻出现的整个值。非原子加载和存储不提供这些保证。
对列表的任何操作都不是原子操作,因此需要格外小心,使用锁、事件、条件或信号量等使其线程安全。这在列表是否是线程安全的中进行了解释。
| 归档时间: |
|
| 查看次数: |
5621 次 |
| 最近记录: |