views:

58

answers:

2
from threading import *
from time import *

class MyThread(Thread):
    def __init__(self,x):
     self.x = x
     Thread.__init__(self)
    def run(self):
     sleep(2)
     print(self.x)

if __name__=='__main__':    
    threads = []
    for i in range(5):
     threads.append(MyThread('Hello'))

    for i in range(5):
     threads[i].start()

    for i in range(5):
     threads[i].join()

This code print 'Hello' 10 times but if I comment "sleep(2)" it prints 'Hello' 5 times.
What is the problems with sleep() function? OR Where is the problem? I am using Python3000.

A: 

I think you've found a bug in Python 3 -- I can reproduce your results running under the latest released Py 3.1, but with 2.6 the results are as expected (only five lines emitted either way, though the newlines can get bunched up surprisingly wrt the contents that's within the specs of threaded behavior). Please open a bug at bugs.python.org!!!

Alex Martelli
+2  A: 

It looks like you've run into the problem documented in Python bug tracker issue 6750. Fixes for the problem are checked in and will appear in the next maintenance release of Python 3.1, if there is one, or in Python 3.2.

$ python3.1 test_thread.py 
Hello
Hello
Hello
Hello
Hello
Hello
Hello
$ python3.2 test_thread.py 
Hello
Hello
Hello
Hello
Hello
Ned Deily
(+1A)Thanks. It seems like I'll have to work with an earlier version for a while.
TheMachineCharmer