python-multithreadingpython-3.9

Python 3.9.13 multithreading issue


Context: I'm making a program that's going to take control of my keyboard. I'm attempting to use a thread to act as a kill button for the program. I've been referencing How to run multiple functions at the same time? and while I'm not getting errors, the threads are also not running in parallel

The results: I'm currently only seeing the Kill function active- getting the debug print line. As it stands, I'm expecting this to be some kind of unexpected interaction between the threading and the keyboard.wait() function. It's also potentially from Visual Studio, but I'm not expecting this to be the issue.

The question: How do I get the program to properly do this as a mulithread?

The Code:

    import ctypes  #this isn't being used yet, but I'm including it in case it's a problem
    import sys
    import keyboard
    from threading import Thread

    def KILL():
        print("press q to end program")
        keyboard.wait('q');
        print("Exited")
        sys.exit()

    def Primary():
        print("secondary thread")
        keyboard.wait('w')
        print("ending program")

    if __name__ == '__main__':
        Thread(target= KILL()).start()
        Thread(target= Primary()).start()

I've tried changing from keyboard.on_input() to keyboard.wait(), which is presumably a good change, since it's not running a loop on that anymore.

I've changed from importing all of threading to just the Thread portion, this hasn't changed the outputs


Solution

  • The problem is that instead of passing a function as the value of the target parameter, you are calling the function:

    Thread(target= KILL()).start()
    

    You need:

    Thread(target=KILL).start()
    

    Remember that arguments are evaluated before a function is called.


    You're also creating too many threads; don't forget that you already have one thread executing -- the main process. You only need to start a single background thread:

    import sys
    import keyboard
    from threading import Thread
    
    def KILL():
        print("press q to end program")
        keyboard.wait('q');
        print("Exited")
        sys.exit()
    
    def Primary():
        print("secondary thread")
        keyboard.wait('w')
        print("ending program")
    
    if __name__ == '__main__':
        Thread(target=KILL).start()
        Primary()
    

    Lastly, note that calling sys.exit() in one thread will not necessarily cause your program to exit.