user845459
user845459

Reputation:

Terminate a python thread based on a flag

I create a python thread.One it's kick to run by calling it's start() method , I monitor a falg inside the thread , if that flag==True , I know User no longer wants the thread to keep running , so I liek to do some house cleaning and terminate the thread.

I couldn't terminate the thread however. I tried thread.join() , thread.exit() ,thread.quit() , all throw exception.

Here is how my thread looks like .

EDIT 1 : Please notice the core() function is called within standard run() function , which I haven't show it here.

EDIT 2 : I just tried sys.exit() when the StopFlag is true , and it looks thread terminates ! is that safe to go with ?

class  workingThread(Thread):

    def __init__(self, gui, testCase):
        Thread.__init__(self)
        self.myName = Thread.getName(self)
        self.start()    # start the thread

    def core(self,arg,f) : # Where I check the flag and run the actual code

        # STOP
        if (self.StopFlag == True):
            if self.isAlive():

                self.doHouseCleaning()
                # none of following works all throw exceptions    
                self.exit()
                self.join()
                self._Thread__stop()
                self._Thread_delete()
                self.quit()

            # Check if it's terminated or not
            if not(self.isAlive()):
               print self.myName + " terminated " 



        # PAUSE                                                        
        elif (self.StopFlag == False) and not(self.isSet()):

            print self.myName + " paused"

            while not(self.isSet()):
                pass

        # RUN
        elif (self.StopFlag == False) and self.isSet():
            r = f(arg)            

Upvotes: 2

Views: 4048

Answers (2)

damzam
damzam

Reputation: 1961

There's no explicit way to kill a thread, either from a reference to thread instance or from the threading module.

That being said, common use cases for running multiple threads do allow opportunities to prevent them from running indefinitely. If, say, you're making connections to an external resource via urllib2, you could always specify a timeout:

import urllib2
urllib2.urlopen(url[, data][, timeout])

The same is true for sockets:

import socket
socket.setdefaulttimeout(timeout)

Note that calling the join([timeout]) method of a thread with a timeout specified will only block for hte timeout (or until the thread terminates. It doesn't kill the thread.

If you want to ensure that the thread will terminate when your program finishes, just make sure to set the daemon attribute of the thread object to True before invoking it's start() method.

Upvotes: 0

engineerC
engineerC

Reputation: 2868

Several problems here, could be others too but if you're not showing the entire program or the specific exceptions this is the best I can do:

  1. The task the thread should be performing should be called "run" or passed to the Thread constructor.
  2. A thread doesn't call join() on itself, the parent process that started the thread calls join(), which makes the parent process block until the thread returns.
  3. Usually the parent process should be calling run().
  4. The thread is complete once it finishes (returns from) the run() function.

Simple example:

import threading
import time

class MyThread(threading.Thread):

    def __init__(self):
        super(MyThread,self).__init__()
        self.count = 5

    def run(self):
        while self.count:
            print("I'm running for %i more seconds" % self.count)
            time.sleep(1)
            self.count -= 1

t = MyThread()
print("Starting %s" % t)
t.start()
# do whatever you need to do while the other thread is running
t.join()
print("%s finished" % t)

Output:

Starting <MyThread(Thread-1, initial)>
I'm running for 5 more seconds
I'm running for 4 more seconds
I'm running for 3 more seconds
I'm running for 2 more seconds
I'm running for 1 more seconds
<MyThread(Thread-1, stopped 6712)> finished

Upvotes: 3

Related Questions