Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

multithreading - How terminate Python thread without checking flag continuously

class My_Thread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        print "Starting " + self.name
        cmd = [ "bash", 'process.sh']
        p = subprocess.Popen(cmd,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
        for line in iter(p.stdout.readline, b''):
            print ("-- " + line.rstrip())
        print "Exiting " + self.name

    def stop(self):
        print "Trying to stop thread "
        self.run = False

thr = My_Thread()
thr.start()
time.sleep(30)
thr.stop()
thr.join()

So i have thread like show above, actually work on windows and process.sh is bash script which run in cygwin and takes around 5 min to finish execution so its not a loop its some simulation proecess

i want to create stop() function in this class so that i can terminate script immediately when i want. after termination i am not expecting any useful result from process.sh script

please can u suggest any method, If possible please give little explanation too..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For your particular example, it's probably easiest to terminate the thread by terminating the subprocess it spawns using the Popen object's terminate() method...

class My_Thread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.process = None

    def run(self):
        print "Starting " + self.name
        cmd = [ "bash", 'process.sh']
        self.process = p = subprocess.Popen(cmd,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
        for line in iter(p.stdout.readline, b''):
            print ("-- " + line.rstrip())
        print "Exiting " + self.name

    def stop(self):
        print "Trying to stop thread "
        if self.process is not None:
            self.process.terminate()
            self.process = None

thr = My_Thread()
thr.start()
time.sleep(30)
thr.stop()
thr.join()

...causing a SIGTERM to be sent to bash, and the next call to p.stdout.readline() to raise an exception, which will terminate the thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...