Python线程奇怪的行为
此代码打印“Hello”10次,但如果我注释“sleep(2)”,它将打印“Hello”5次。Python线程奇怪的行为,python,multithreading,Python,Multithreading,此代码打印“Hello”10次,但如果我注释“sleep(2)”,它将打印“Hello”5次。 sleep()函数有什么问题?或者问题出在哪里? 我使用的是Python3000。我认为您在Python3中发现了一个bug——我可以在最新发布的Py3.1下重现您的结果,但在2.6中,结果与预期的一样(无论哪种方式,都只会发出五行,尽管换行符会与线程行为规范中的内容惊人地聚集在一起)。请打开一个错误在 看起来您遇到了Python bug tracker中记录的问题。该问题的修复已签入,并将出现在Py
sleep()函数有什么问题?或者问题出在哪里?
我使用的是Python3000。我认为您在Python3中发现了一个bug——我可以在最新发布的Py3.1下重现您的结果,但在2.6中,结果与预期的一样(无论哪种方式,都只会发出五行,尽管换行符会与线程行为规范中的内容惊人地聚集在一起)。请打开一个错误在 看起来您遇到了Python bug tracker中记录的问题。该问题的修复已签入,并将出现在Python 3.1的下一个维护版本(如果有)或Python 3.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()
无论
sleep()
调用是否被注释,程序都会为我打印5次“Hello”。由于您只创建了5个线程,每个线程只打印“Hello”一次,因此我不认为代码打印“Hello”的次数会超过5次。(+1A)谢谢。看来我得用一段时间以前的版本了。
$ python3.1 test_thread.py
Hello
Hello
Hello
Hello
Hello
Hello
Hello
$ python3.2 test_thread.py
Hello
Hello
Hello
Hello
Hello