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

Hendrik van Rooyen hendrik at microcorp.co.za
Thu Sep 17 05:18:35 EDT 2009


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:
        time.sleep(1)

hvr at Linuxbox:~/Junk> python -i jjj.py
start time is: 1253176132.64
0
End at: 1253176133.34 That took: 0.700681209564 seconds
start time is: 1253176133.34
9999999
End at: 1253176134.18 That took: 0.847566127777 seconds
Traceback (most recent call last):
  File "jjj.py", line 18, in <module>
    time.sleep(1)
KeyboardInterrupt
>>>
No simultaneity.
So when I increase the range to a hundred million to try to force some 
concurrency, I get:

hvr at Linuxbox:~/Junk> python -i jjj.py
Killed
hvr at Linuxbox:~/Junk>      

The behaviour is that it just thrashes for some minutes and then it looks like 
the os kills it.

SuSe Linux, dual core Intel with a gig of memory:

Python 2.5.1 (r251:54863, Dec  6 2008, 10:49:39)
[GCC 4.2.1 (SUSE Linux)] on linux2

I enclose the file.

- Hendrik

-------------- next part --------------
A non-text attachment was scrubbed...
Name: jjj.py
Type: application/x-python
Size: 395 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20090917/e25d3663/attachment.bin>


More information about the Python-list mailing list