在while循环中运行线程是否可能?

3

我正在尝试在while循环中运行一个线程,但是出现了错误 RuntimeError: threads can only be started once 请建议一种修复方法。

import sys
import threading
import time

import keyboard


def hd():
    time.sleep(1)
    print("hello")


cc = threading.Thread(target=hd)

while True:
    time.sleep(3)
    if keyboard.is_pressed("q"):
        print("Q is pressed")
        sys.exit()
    else:
        if not cc.is_alive():
            cc.start()

你是否正在尝试定期调用hd(),直到键盘上按下Q键? - Kris
在循环之前只启动线程一次。只要按下 Q 键就停止它。 - OneCricketeer
1个回答

0

看看这篇文章:link。它提供了一些对你的问题有启发性的见解。

线程基本上在完成后就被销毁了。将else语句编辑为类似以下内容可能会完成手头的任务:

if not cc.is_alive():
        cc = threading.Thread(target=hd)
        cc.start()

1
这不会导致线程泄漏吗?你应该停止现有的线程,而不是取消引用并启动一个新线程。 - OneCricketeer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接