In Python, suppose one thread is appending/popping items to/from a list
/collections.deque
/similar built-in container, while another thread occasionally empties the container via its clear()
method. Is this interaction thread-safe? Or is it possible for the clear()
to interfere with a concurrent append()
/pop()
operation, leaving the list uncleared or corrupted?
My interpretation of the accepted answer here suggests that the GIL should prevent such interference, at least for lists. Am I correct?
As a related follow-up, if this is not thread-safe, I suppose I should use a queue.Queue
instead. But what is the best (i.e., cleanest, safest, fastest) way to clear it from the second thread? See the comments on this answer for concerns about using the (undocumented) queue.Queue().queue.clear()
method. Need I really use a loop to get()
all the items one by one?