How to close a thread from within?

PythonMultithreading

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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 https://docs.python.org/3/library/threading.html">this</a>;, you can also call thread.exit(), which will throw an exception that will end the thread silently.

Solution 2 - Python

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: https://stackoverflow.com/questions/905189/why-does-sys-exit-not-exit-when-called-inside-a-thread-in-python

Solution 3 - Python

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)

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionskeritView Question on Stackoverflow
Solution 1 - PythonBrendan LongView Answer on Stackoverflow
Solution 2 - PythonkryptokinghtView Answer on Stackoverflow
Solution 3 - PythonEric FossumView Answer on Stackoverflow
Solution 4 - PythoniFA88View Answer on Stackoverflow