【问题标题】:Python time.sleep kills the ThreadPython time.sleep 杀死线程
【发布时间】:2021-11-13 10:47:29
【问题描述】:

我在 Windows 上使用 Portable Python 3.9.4 x64,每次我调用 time.sleep(...) 方法时,线程都会退出并且不会返回:

import threading
import time

threads = []
print ("hello")

class myThread(threading.Thread):
    def __init__(self, i):
        threading.Thread.__init__(self)
        self.i = i

    def run(self):
        print ("i = ", self.i)
        for j in range(0, self.i):
            print ("i: ", i,"j = ",j)
            time.sleep(5)

for i in range(1,4):
    thread = myThread(i)
    thread.daemon = False
    thread.start()

我的输出是:

hello
i =  1
i:  1 j =  0
i =  2
i:  2 j =  0
i =  3
i:  3 j =  0

如果我使用更短的延迟,例如time.sleep(0.05),那么我会得到更多的 j 值,但仍然不是全部。 所以我猜所有线程都被杀死了,因为主线程完成了。但是我怎样才能保持线程运行呢? daemon-attribute 似乎没有改变任何东西......

【问题讨论】:

    标签: python multithreading sleep daemon


    【解决方案1】:

    我认为你的 time.py 模块文件有问题。如果您使用的是本地,请重新下载文件,或者如果您在线,请尝试联系并报告此问题。

    【讨论】:

    猜你喜欢
    • 2011-04-19
    • 1970-01-01
    • 2022-11-29
    • 2023-02-01
    • 1970-01-01
    • 2015-04-22
    • 2014-10-24
    • 2016-07-10
    • 1970-01-01
    相关资源
    最近更新 更多