4

当第二个线程完成时,有什么方法可以停止第一个线程?

例子:

from functools import partial

import threading

def run_in_threads(*functions):
    threads=[]

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

    for thread in threads:
        thread.join()

def __print_infinite_loop(value):
    while True:print(value)

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

if __name__=="__main__":
    run_in_threads(partial(__print_infinite_loop,"xyz"),partial(__print_my_value_n_times,"123",1000))))))

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

4

1 回答 1

1

你可以使用threading.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)
于 2012-11-24T14:56:34.910 回答