例:
from functools import partialimport threadingdef 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))))))
在上面的例子中,我在线程中运行两个函数,并且我必须在第二个线程完成时停止第一个线程.我读到它支持事件,但不幸的是我还没有使用它.
解决方法 你可以像这样使用threading.Event:import functoolsimport threadingdef 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,10,event) run_in_threads(infinite_loop,my_values)总结
以上是内存溢出为你收集整理的如何在python中完成第二个线程时停止第一个线程?全部内容,希望文章能够帮你解决如何在python中完成第二个线程时停止第一个线程?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)