7

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.

Community
  • 1
  • 1
john smith
  • 507
  • 6
  • 18

1 Answers1

4

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.

Community
  • 1
  • 1
Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37
  • 2
    You linked a bunch of tangentially related stuff talking about what atomic means, but provided no justification or evidence that (at least in CPython) list pop is _actually_ atomic. Your linked SO question has this detail, though. – GManNickG Apr 13 '18 at 01:01