简体   繁体   English

暂停 python 中的线程

[英]Pausing thread in python

I want to pause and continue threads if a certain key is pressed.如果按下某个键,我想暂停并继续线程。 I tried: if q is pressed it will remove(change to 0) the "time.sleep(99999)" but it didnt work can anyone help me?我试过:如果按下 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()

You can create a class for this您可以为此创建一个 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()

And we will call the stop() function when user hits q .当用户点击q时,我们将调用stop() function 。

def test1():
    if keyboard.is_pressed("q"):  
        Thread1.stop()  

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

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