Python: how to interrupt raw_input () in another thread

I am writing a simple client-server program in python. In the client program, I create two threads (using the Pingon threading module), one for receiving, one for sending. The receiving stream continuously receives rows from the server side; while the sending stream continuously listens for user input (using raw_input ()) and sends it to the server. Two threads exchange data using a queue (which is synchronized initially, LIKE!).

The basic logic is as follows:

Receiving a stream:

global queue = Queue.Queue(0) def run(self): while 1: receive a string from the server side if the string is QUIT signal: sys.exit() else: put it into the global queue 

Sending stream:

 def run(self): while 1: str = raw_input() send str to the server side fetch an element from the global queue deal with the element 

As you can see, in the receiving stream I have an if condition to check if the server sent the client a β€œQUIT signal”. If so, I want the whole program to stop.

The problem is that for most of its time, the send stream is blocked by "raw_input ()" and awaits user input. When it is blocked, calling "sys.exit ()" from another stream (receiving stream) will not immediately terminate the transmission stream. The sending stream must wait for the user to type something and press the enter button.

Can anyone inspire me how to get around this? I am not opposed to using alternatives to "raw_input ()". In fact, I don't even mind changing the whole structure.

------------- ------------- EDIT

I run this on a Linux machine, and my Python version is 2.7.5

+6
source share
1 answer

You can simply create a daemonic send stream:

 send_thread = SendThread() # Assuming this inherits from threading.Thread send_thread.daemon = True # This must be called before you call start() 

The Python interpreter will not be blocked from exiting unless the remaining threads remain daemons. So, if only the remaining thread is send_thread , your program will exit, even if you are blocked on raw_input .

Note that this will abruptly terminate the sending stream, no matter what it does. This can be dangerous if it refers to external resources that need to be cleaned correctly or should not be interrupted (for example, write to a file). If you do something like this, protect it with threading.Lock and only call sys.exit() from the receiving stream if you can get the same Lock .

+4
source

Source: https://habr.com/ru/post/975673/


All Articles