Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,当第二个线程完成时,如何停止第一个线程?_Python_Multithreading_Python Multithreading - Fatal编程技术网

在python中,当第二个线程完成时,如何停止第一个线程?

在python中,当第二个线程完成时,如何停止第一个线程?,python,multithreading,python-multithreading,Python,Multithreading,Python Multithreading,当第二个线程完成时,有没有办法停止第一个线程 例如: 从functools导入部分 导入线程 def在线程中运行(*函数): 线程=[] 对于函数中的函数: 线程=线程。线程(目标=函数) thread.start() 附加(线程) 对于线程中的线程: thread.join() 定义打印无限循环(值): 为True时:打印(值) 定义打印我的值n次(值,n): 对于范围(n)中的i:打印(值) 如果名称=“\uuuuu main\uuuuuuuu”: 在线程中运行(部分(uu print_in

当第二个线程完成时,有没有办法停止第一个线程

例如:

从functools导入部分
导入线程
def在线程中运行(*函数):
线程=[]
对于函数中的函数:
线程=线程。线程(目标=函数)
thread.start()
附加(线程)
对于线程中的线程:
thread.join()
定义打印无限循环(值):
为True时:打印(值)
定义打印我的值n次(值,n):
对于范围(n)中的i:打印(值)
如果名称=“\uuuuu main\uuuuuuuu”:
在线程中运行(部分(uu print_infinite_loop,“xyz”)、部分(u print_my_value_n_times,“123”,1000‘‘‘‘‘‘‘‘‘‘‘‘‘)

在上面的AxSample中,我在线程中运行了两个函数,当第二个线程完成时,我必须停止第一个线程。我读到它支持by events,但不幸的是,我还没有使用它。

您可以使用
线程。Event
如下所示:

import functools
import threading

def run_in_threads(*functions):
    threads = []

    for function in functions:
        thread = threading.Thread(target = function)
        thread.daemon = True
        thread.start()
        threads.append(thread)

    for thread in threads:
        thread.join()

def __print_infinite_loop(value, event):
    while not event.is_set():
        print(value)

def __print_my_value_n_times(value, n, event):
    for i in range(n):
        print(value)
    event.set()

if __name__ == "__main__":
    event = threading.Event()
    infinite_loop = functools.partial(__print_infinite_loop, "xyz", event)
    my_values = functools.partial(__print_my_value_n_times, "123", 10, event)
    run_in_threads(infinite_loop, my_values)