skerit skerit - 5 months ago 9x
Python Question

How to close a Python thread from within

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

# And thread it

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:

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


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.