Python 3.x python库中的终止线程

Python 3.x python库中的终止线程,python-3.x,multithreading,Python 3.x,Multithreading,我正在编写一个将在unix/windows上使用的python库。我面临终止t1线程的问题。我曾尝试将其设置为守护进程线程,但由于该库有时在IDE/应用程序中使用,t1线程在整个应用程序关闭之前不会关闭,这是不需要的。现在,我尝试将其更改为非守护进程线程,并手动处理终止 def threadclick(id, stop): while(True): //do things repetitively // if stop(): brea

我正在编写一个将在unix/windows上使用的python库。我面临终止
t1
线程的问题。我曾尝试将其设置为
守护进程
线程,但由于该库有时在IDE/应用程序中使用,
t1
线程在整个应用程序关闭之前不会关闭,这是不需要的。现在,我尝试将其更改为非守护进程线程,并手动处理终止

def threadclick(id, stop):
    while(True):
        //do things repetitively //
        if stop():
           break

def main():
    global stop_thread
    stop_thread = False
    port_string1 = port_string
    t1 = threading.Thread(target=threadclick, args=(id, lambda : stop_thread))
    t1.start()
我需要能够通过调用此函数来关闭它:

def close_thread():
     global stop_thread
     stop_thread = True
     t1.join

当然,它给了我t1是未定义的错误,但我不确定如何全局声明它。

传递从简单标量读取的常量值, 而不是传递一个参考,是一个问题, 因为你不想继续重读一个不变的值。 口述会很方便

您使用的函数似乎有点复杂

另外,你最好还是传一封推荐信, 而不是依赖一个全球性的

使用以下命令:

def threadclick(id, status):
    while not status['stop']:
        do_things()


status = dict(stop=False)


def main():
    status['stop'] = False
    t1 = threading.Thread(target=threadclick, args=(id, status))
    t1.start()
    wait_for_things_to_happen()
    close_thread(t1, status)


def close_thread(t1, status):
    status['stop'] = True
    t1.join()

谢谢你的帮助!有没有一种方法可以在不传递t1或状态的情况下调用close_thread()函数?用户将导入库,他应该在应用程序结束时调用close_线程函数,而不传递参数。(实际上,我正在将close_thread()函数组合到另一个库的函数-serial_port.close()中)听起来您想使用上下文管理器。考虑使用<代码>关闭(…)< /代码>