Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is list.pop thread safe in python [duplicate]

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")

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.

like image 592
john smith Avatar asked Oct 30 '22 17:10

john smith


1 Answers

My answer would be YES - To get element out(pop) of global list which is used by multiple threads at a time, is thread safe

Reason is because it is atomic operation.

One operation at a time is atomic operation.

Check this link.

From above 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.

Any manipulation on list won't be atomic operation, so extra care need to be taken to make it thread safe using Lock, Event, Condition or Semaphores etc. This is explained in Are lists thread-safe here.

like image 198
Dinesh Pundkar Avatar answered Nov 15 '22 06:11

Dinesh Pundkar