Are min() and max() thread-safe?

John Nagle nagle at animats.com
Thu Sep 17 04:01:09 EDT 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 
> simultaneously?
> 
> 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

	http://effbot.org/zone/thread-synchronization.htm

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.

				John Nagle



More information about the Python-list mailing list