【问题标题】:Pausing thread in python在python中暂停线程
【发布时间】:2021-05-29 02:12:42
【问题描述】:

如果按下某个键,我想暂停并继续线程。 我试过:如果按下 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()

【问题讨论】:

标签: python python-3.x multithreading keyboard python-multithreading


【解决方案1】:

您可以为此创建一个类

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()  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2018-11-04
    • 2016-03-26
    • 2020-08-13
    相关资源
    最近更新 更多