ammar
ammar

Reputation: 64

How to implement blocking listening function in separate thread while the main keeps working in Python

I have main method in module main.py which calls a method in another module called listener.py. They look like this.

main.py

def main():
   listener.start_server()
   print("Test")



listener.py

def start_server():
    t_server = threading.Thread(target=server.start)
    t_server.start()
    # signal.pause()

The listener thread is calling a class function in another module called server.py which has WHILE loop that blocks.

I don't want my main method to block, and it prints ("Test") indeed. However, than I am not able to catch KeyboardInterrupt in the listening thread, and that is why I need signal.pause(). When I use signal.pause() the main thread blocks and the print statement is not executed until the listening thread is finished. Is there any way to combine these two so that the main thread does not block when using signal.pause()?

Upvotes: 1

Views: 188

Answers (1)

ammar
ammar

Reputation: 64

For all the people who will come across this problem here is the simple solution: IMPLEMENT SIGNAL HANDLER AND DO NOT USE signal.pause()

By implementing signal handler, the main method will continue to work, i.e the method in which the thread was created won't block. It is a simple solution I did not come across.

So instead of using:signal.pause() use this:

def start_server():
   t_server = threading.Thread(target=server.start)
   t_server.start()
   # signal.pause()
   signal.signal(signal.SIGINT, handler)

def handler(signum, frame):
   ... # do whaterver you want to do, throw an exception, close your resources etc.

Upvotes: 1

Related Questions