62

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], globQueueIndex, serverQueue )

# Start it
c.start()

# And thread it
self.threads.append(c)

Now, I know I can close all the threads using this code:

    # Loop through all the threads and close (join) them
    for c in self.threads:
        c.join()

But how can I close the thread from within that thread?

martineau
  • 119,623
  • 25
  • 170
  • 301
Jelle De Loecker
  • 20,999
  • 27
  • 100
  • 142
  • 8
    `.join()` does not close a thread, everything it does is _waiting_ (by blocking the calling thread) for the joined thread to terminate itself. – Darkonaut Aug 22 '18 at 15:48

4 Answers4

82

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.

Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
Brendan Long
  • 53,280
  • 21
  • 146
  • 188
  • 44
    thread.exit() only works with the thread object, but not with threading.Thread class object. – moeabdol Mar 07 '15 at 20:09
  • 5
    Looks like exit() method is not available in python 3.7 After calling: threading.enumerate()[1].exit() I am getting an error: AttributeError: 'Thread' object has no attribute 'exit' Is there any alternative? – Dounchan Oct 28 '19 at 19:40
35

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?

kryptokinght
  • 539
  • 5
  • 12
29

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)

Eric Fossum
  • 2,395
  • 4
  • 26
  • 50
6

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

iFA88
  • 69
  • 2
  • 1
  • 3
    To improve your answer, you should include _when_ it is a better alternative than the others listed here, along with a link to some documentation to support it. – The Unknown Dev Feb 16 '18 at 13:27