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

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Sep 17 01:39:25 EDT 2009


On Wed, 16 Sep 2009 22:08:40 -0700, Miles Kaufmann wrote:

> On Sep 16, 2009, at 9:33 PM, 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?
> 
> See for yourself:
> http://svn.python.org/view/python/trunk/Python/bltinmodule.c?view=markup

Mostly gobbledygook to me I'm afraid  :( 


> 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.



Nevertheless, this is useful information to know, thank you.



-- 
Steven



More information about the Python-list mailing list