python 线程库执行新活动

问题描述 投票:0回答:1

请注意这个简单的程序:

从时间导入睡眠

从线程导入线程

def fun1():

睡觉(10)

线程1 = 线程(目标 = fun1)

线程1.start()

#签名

睡眠(100)

打印(“你好”)

当 thread1 完成时,如何停止执行 #sign 下面的代码。

谢谢您的帮助

python-3.x parallel-processing python-multithreading
1个回答
0
投票

这是一种解决方案。您可以选择休眠一秒,同时使用

count
变量监控经过的时间,而不是休眠 100 秒(这会导致主程序在整个期间处于非活动状态)。这样做就无需在 func1 完成后等待程序结束 100 秒。线程终止后,程序将结束,因为条件
thread1.is_alive()
将被评估为 false

from time import sleep
from threading import Thread

def fun1():
    sleep(10)
    print("Fun1 done")


if __name__ == "__main__":
    thread1 = Thread(target=fun1)
    thread1.start()

    count = 0
    while thread1.is_alive():
        sleep(1)
        count += 1
        if count >= 100:  # Wait for 100 seconds
            print("hello")  # Sign content
            count = 0

    thread1.join()
© www.soinside.com 2019 - 2024. All rights reserved.