Are min() and max() thread-safe?
pavlovevidence at gmail.com
Thu Sep 17 12:57:18 CEST 2009
On Sep 17, 2:18 am, Hendrik van Rooyen <hend... at microcorp.co.za>
> On Thursday 17 September 2009 06:33:05 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?
> Apart from the plethora of indirection, nothing I can see.
> But there is something rotten. Going more basic, look at this:
> hvr at Linuxbox:~/Junk> cat jjj.py
> import thread as th
> import time
> a = range(10000000)
> def worker(func,thing):
> start_time = time.time()
> print "start time is:",start_time
> res = func(thing)
> print res
> end_time = time.time()
> print "End at:",end_time,"That took:",end_time-start_time, 'seconds'
> t1 = th.start_new_thread(worker,(min,a))
> t2 = th.start_new_thread(worker,(max,a))
> while True:
> hvr at Linuxbox:~/Junk> python -i jjj.py
> start time is: 1253176132.64
> End at: 1253176133.34 That took: 0.700681209564 seconds
> start time is: 1253176133.34
> End at: 1253176134.18 That took: 0.847566127777 seconds
> Traceback (most recent call last):
> File "jjj.py", line 18, in <module>
> No simultaneity.
When running min or max on a list of ints, there is probably no
occasion for the function to release the GIL. If a thread doesn't
release the GIL no other Python threads can run. This behavior may be
rotten, but it's totally expected.
Try adding "key=lambda x:x" to the function call (which adds an
occasion where the GIL might be released); you will see that it will
More information about the Python-list