How to close a thread from within?

后端 未结 4 1039
日久生厌
日久生厌 2020-12-02 14:16

For every client connecting to my server I spawn a new thread, like this:

# Create a new client
c = Client(self.server.accept(), globQueue[globQueueIndex], g         


        
相关标签:
4条回答
  • 2020-12-02 14:47

    When you start a thread, it begins executing a function you give it (if you're extending threading.Thread, the function will be run()). To end the thread, just return from that function.

    According to this, you can also call thread.exit(), which will throw an exception that will end the thread silently.

    0 讨论(0)
  • 2020-12-02 14:50

    How about sys.exit() from the module sys.

    If sys.exit() is executed from within a thread it will close that thread only.

    This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?

    0 讨论(0)
  • 2020-12-02 15:01

    If you want force stop your thread: thread._Thread_stop() For me works very good.

    0 讨论(0)
  • 2020-12-02 15:03

    A little late, but I use a _is_running variable to tell the thread when I want to close. It's easy to use, just implement a stop() inside your thread class.

    def stop(self):
      self._is_running = False
    

    And in run() just loop on while(self._is_running)

    0 讨论(0)
提交回复
热议问题