Pratik Deoghare
Pratik Deoghare

Reputation: 37172

Python threading strange behaviour

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.

Upvotes: 0

Views: 230

Answers (2)

Ned Deily
Ned Deily

Reputation: 85025

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

Upvotes: 2

Alex Martelli
Alex Martelli

Reputation: 881477

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

Upvotes: 0

Related Questions