Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A fundamental issue with Python threads is that <strong>you can't just kill them - they have to agree to die</strong>.</p> <p>What you should do is:</p> <ol> <li>Implement the thread as a class</li> <li>Add a <code>threading.Event</code> member which the <code>join</code> method clears and the thread's main loop occasionally checks. If it sees it's cleared, it returns. For this override <code>threading.Thread.join</code> to check the event and then call <code>Thread.join</code> on itself</li> <li>To allow (2), make the read from <code>Queue</code> block with some small timeout. This way your thread's "response time" to the kill request will be the timeout, and OTOH no CPU choking is done</li> </ol> <p>Here's some code from a socket client thread I have that has the same issue with blocking on a queue:</p> <pre><code>class SocketClientThread(threading.Thread): """ Implements the threading.Thread interface (start, join, etc.) and can be controlled via the cmd_q Queue attribute. Replies are placed in the reply_q Queue attribute. """ def __init__(self, cmd_q=Queue.Queue(), reply_q=Queue.Queue()): super(SocketClientThread, self).__init__() self.cmd_q = cmd_q self.reply_q = reply_q self.alive = threading.Event() self.alive.set() self.socket = None self.handlers = { ClientCommand.CONNECT: self._handle_CONNECT, ClientCommand.CLOSE: self._handle_CLOSE, ClientCommand.SEND: self._handle_SEND, ClientCommand.RECEIVE: self._handle_RECEIVE, } def run(self): while self.alive.isSet(): try: # Queue.get with timeout to allow checking self.alive cmd = self.cmd_q.get(True, 0.1) self.handlers[cmd.type](cmd) except Queue.Empty as e: continue def join(self, timeout=None): self.alive.clear() threading.Thread.join(self, timeout) </code></pre> <p>Note <code>self.alive</code> and the loop in <code>run</code>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload