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

Hrvoje Niksic hniksic at xemacs.org
Thu Sep 17 02:26:23 EDT 2009


Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes:

>> min() and max() don't release the GIL, so yes, they are safe, and
>> shouldn't see a list in an inconsistent state (with regard to the
>> Python interpreter, but not necessarily to your application).  But a
>> threaded approach is somewhat silly, since the GIL ensures that they
>> *won't* walk over the same list simultaneously (two separate lists,
>> for that matter).
>
> Perhaps that's true for list contents which are built-ins like ints,
> but with custom objects, I can demonstrate that the two threads
> operate simultaneously at least sometimes. Unless I'm misinterpreting
> what I'm seeing.

If min and max call into Python code, which can happen for custom
objects, then the interpreter will occasionally release the GIL to give
other threads a chance to run.  That way min and max will operate
interleaved (if not exactly in parallel).  Even so, I see no reason for
them to break.



More information about the Python-list mailing list