简体   繁体   中英

How to kill thread from inside another thread?

I have two functions that are threads (using threading). I would like to kill the first thread by the second thread, once a requirement is satisfied, and allow the second thread to continue running. In code, this is what it looks like:

import threading
import time


def functA():
    print("functA started")
    while(1):
        time.sleep(100)

def functB(thread1):
    print("functB started")
    thread1.start()
    x=0
    while(x<3):
        x=x+1
        time.sleep(1)
        print(x)
    print(threading.enumerate())
    thread1.exit() #<---- kill thread1 while thread2 continues....
    while(1):
        #continue doing something....
        pass

thread1 = threading.Thread(target=functA)
thread2 = threading.Thread(target=functB,args=(thread1,))
thread2.start()

How can I kill thread1 from inside of thread2 and continue to keep thread2 running?

Here's how to use a shutdown flag:

thread_a_active = True

def functA():
    print("functA started")
    while thread_a_active:
        time.sleep(1)

def functB(thread1):
    print("functB started")
    thread1.start()
    x=0
    while x<3:
        x=x+1
        time.sleep(1)
        print(x)
    print(threading.enumerate())
    thread_a_active = False
    while True:
        #continue doing something....
        pass

BTW, while and if statements in Python do not use outer parentheses. That's a bad habit carried over by C programmers.

You can kill thread1 from inside of thread2 once thread1 completed its job then you can just do thread1.join() it will kill the thread1. as you put thread1 in loop it wont kill it until it completes its run until you have to wait for it. so join it when you think thread1 is done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM