pythonmultithreadingglobal-variableslocal-variables

How to join thread from another function


I have some code like:

import threading
import time

mode1=False
mode2=True

stop_thread=False

def function1():
     while True:
        print('function1')
        
        global stop_thread
        if stop_thread:
            break
def function2():
    while True:
        print('function2')
        
        global stop_thread
        if stop_thread:
            break

class MyClass():
    def run(self):
        if mode1:
            t = threading.Thread(target=function1, daemon=True)
            t.start()
        elif mode2:
            t = threading.Thread(target=function2, daemon=True)
            t.start()

    def stop(self):
        global stop_thread
        stop_thread=True
        # t.join() doesn't work here

        
v=MyClass()
v.run()
v.stop()

How can I make it possible to join() the thread from stop()?


Solution

  • You just need to save the reference to the thread as an attribute of the MyClass instance:

    import threading
    import time
    
    mode1 = False
    
    stop_thread = False
    
    def function1():
         while True:
            print('function1')
    
            if stop_thread:
                break
    
    def function2():
        while True:
            print('function2')
    
            if stop_thread:
                break
    
    # t=None
    class MyClass():
        def run(self):
            fn = function1 if mode1 else function2
            # Save reference to the thread as an attribute of this instance:
            self.t = threading.Thread(target=fn, daemon=True)
            self.t.start()
    
        def stop(self):
            global stop_thread #,t
    
            stop_thread = True
            self.t.join()
            print('thread has been joined')
    
    
    v = MyClass()
    v.run()
    v.stop()
    

    Prints:

    function2
    thread has been joined