Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a 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
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?

like image 216
skerit Avatar asked Dec 27 '10 19:12

skerit


People also ask

Can a thread close itself?

Yes, it doesn't. I guess it can be confusing because e.g. Thread. sleep() affects the current thread, but Thread. sleep() is a static method.

Can a thread kill itself Python?

Short answer: Just make the def run() end. So, if you are waiting for data from a socket, do it with timeout, then if timeout occur just break the while that you should have, and the thread will be killed. You can check from main thread if a thread is alive with isAlive() method.


4 Answers

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.

like image 108
Brendan Long Avatar answered Oct 05 '22 23:10

Brendan Long


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?

like image 22
kryptokinght Avatar answered Oct 05 '22 21:10

kryptokinght


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)

like image 33
Eric Fossum Avatar answered Oct 05 '22 23:10

Eric Fossum


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

like image 24
iFA88 Avatar answered Oct 05 '22 21:10

iFA88