繁体   English   中英

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()

这段代码打印“ Hello” 10次​​,但是如果我注释“ sleep(2)”,它将打印“ Hello” 5次。
sleep()函数有什么问题? 或问题出在哪里? 我正在使用Python3000。

看来您已经遇到了Python Bug Tracker 发行号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
Hello

我认为您已经在Python 3中发现了一个错误-我可以在最新发布的Py 3.1下运行您的结果,但使用2.6时,结果是按预期进行的(两种方式只发出了5行,尽管新行可以令人惊讶地聚集在一起)包含线程行为规范内的内容)。 请在bugs.python.org中打开错误!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM