Python线程奇怪的行为(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()
此代码打印'你好'10 次,但如果我评论“睡眠(2)”,它打印5次你好。 sleep()函数有什么问题? 或问题在哪里? 我正在使用Python3000。
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.
最满意答案
看起来您已经遇到了Python bug跟踪器问题6750中记录的问题 。 该问题的修复将被检入,并将出现在Python 3.1的下一个维护版本中(如果有的话)或Python 3.2中。
$ python3.1 test_thread.py Hello Hello Hello Hello Hello Hello Hello $ python3.2 test_thread.py Hello Hello Hello Hello HelloIt 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更多推荐
发布评论