Search code examples
pythonpython-3.xmultithreadingkeyboardpython-multithreading

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?

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


Solution

  • You can create a class for this

    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.

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