如何从另一个函数加入线程

问题描述 投票:0回答:1

我的代码看起来像这样:

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

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

    def stop(self):
        global stop_thread #,t
        stop_thread=True
        # t.join()
        
        
v=MyClass()
v.run()
v.stop()

如何在 stop() 函数中 join() 线程?
我尝试将

t
变量设为全局变量,但这不起作用。如果是全局的,则会出现此错误:

单元格输入[4],第 32 行
全球 t
^
语法错误:名称“t”在全局声明之前使用

python multithreading global-variables local-variables
1个回答
0
投票

您只需将对线程的引用保存为

MyClass
实例的属性即可:

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()
time.sleep(.01)
v.stop()

打印:

function2
function2
function2
function2
function2
function2
function2
function2
function2
function2
function2
function2
function2
function2
thread has been joined
© www.soinside.com 2019 - 2024. All rights reserved.