Are min() and max() thread-safe?
nagle at animats.com
Thu Sep 17 10:01:09 CEST 2009
Steven D'Aprano wrote:
> I have two threads, one running min() and the other running max() over
> the same list. I'm getting some mysterious results which I'm having
> trouble debugging. Are min() and max() thread-safe, or am I doing
> something fundamentally silly by having them walk over the same list
> My code is as follows. Is there anything obviously wrong with it?
You don't seem to be modifying the data while iterating over it,
so there's no real race condition issue.
All Python guarantees is that you can't break the underlying memory
model with threading. You're not guaranteed, for example,
that "min" is atomic. There's a short list of primitives whose
atomicity is guaranteed, at
In particular, some operations like appending to a list and
popping an element from a list are atomic, which is useful.
Be aware that CPython performance on multithreaded programs
really sucks on multicore CPUs. Not only does the GIL prevent
two CPUs from doing useful work at the same time, the locking
logic is horribly inefficient for multiprocessors. Adding an
additional CPU actually increases run time as the CPUs fight
over the lock.
So there's little point in doing this.
More information about the Python-list