在 python 中暂停线程
Pausing thread in python
我想在按下某个键时暂停并继续线程。
我试过:如果按下 q,它会删除(更改为 0)“time.sleep(99999)”,但它不起作用有人能帮我吗?
import keyboard
from threading import Thread
from time import sleep
Thread1 = True
Thread2 = True
class main():
def test1():
if keyboard.is_pressed("q"): #if keyboard is pressed q it will reomve the sleep
time = 0
time = 99999
while Thread1 == True:
print("Thread1")
sleep(time)
def test2():
while Thread2 == True:
print("Thread2")
sleep(1)
Thread(target=test1).start()
Thread(target=test2).start()
main()
您可以为此创建一个class
class customThread(threading.Thread):
def __init__(self, *args, **kwargs):
super(customThread, self).__init__(*args, **kwargs)
self.__stop_event = threading.Event()
def stop(self):
self.__stop_event.set()
def stoppped(self):
self.__stop_event.is_set()
当用户点击 q
时,我们将调用 stop()
函数。
def test1():
if keyboard.is_pressed("q"):
Thread1.stop()
我想在按下某个键时暂停并继续线程。 我试过:如果按下 q,它会删除(更改为 0)“time.sleep(99999)”,但它不起作用有人能帮我吗?
import keyboard
from threading import Thread
from time import sleep
Thread1 = True
Thread2 = True
class main():
def test1():
if keyboard.is_pressed("q"): #if keyboard is pressed q it will reomve the sleep
time = 0
time = 99999
while Thread1 == True:
print("Thread1")
sleep(time)
def test2():
while Thread2 == True:
print("Thread2")
sleep(1)
Thread(target=test1).start()
Thread(target=test2).start()
main()
您可以为此创建一个class
class customThread(threading.Thread):
def __init__(self, *args, **kwargs):
super(customThread, self).__init__(*args, **kwargs)
self.__stop_event = threading.Event()
def stop(self):
self.__stop_event.set()
def stoppped(self):
self.__stop_event.is_set()
当用户点击 q
时,我们将调用 stop()
函数。
def test1():
if keyboard.is_pressed("q"):
Thread1.stop()