What kind of "thread safe" are deque's actually?

Travis Griggs travisgriggs at gmail.com
Mon Mar 27 21:25:01 EDT 2023


A while ago I chose to use a deque that is shared between two threads. I did so because the docs say:

"Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.”

(https://docs.python.org/3.11/library/collections.html?highlight=deque#collections.deque)

Earlier today, looking through some server logs I noticed that from time to I’m getting a

RuntimeError: deque mutated during iteration

I guess this surprised me. When I see “thread safe”, I don’t expect to get errors.

Interestingly the error also only started showing up when I switched from running a statistics.mean() on one of these, instead of what I had been using, a statistics.median(). Apparently the kind of iteration done in a mean, is more conflict prone than a median?

I’ve got a couple ways I can work around this. But I was surprised.


More information about the Python-list mailing list