Search code examples
pythonpython-multithreading

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?


Solution

  • 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.