简体   繁体   English

在 python 中终止线程的最佳方法是什么?

[英]What is the best way to terminate a thread in python?

I am implementing a Flask application and I'm calling a function A, based on a request.我正在实施一个 Flask 应用程序,我正在根据请求调用一个 function A。 Inside the function A, there is another function called B and it is called.在 function A 里面,还有一个 function 叫 B ,叫它。 But, I don't need to wait until the end of the execution of function B to return the output from function A. I have done it with the following code implementation.但是,我不需要等到 function B 的执行结束来从 function A 返回 output。我已经完成了以下代码。

from threading import Thread

def functionA():
    result = doSomething1()
    Thread(target=functionB).start()
    return result

def functionB():
    # Do something after the execution of doSomething1()

Here, I am starting a new thread and do what I need to do but, I do not terminate the newly started thread.在这里,我正在启动一个新线程并做我需要做的事情,但是我不会终止新启动的线程。 Do I need to terminate that thread by myself?我需要自己终止那个线程吗? If so, what is the best way to do that?如果是这样,最好的方法是什么?

A thread will terminate on its own.线程将自行终止。 To see if it is alive you can use thread.is_Alive()要查看它是否还活着,您可以使用 thread.is_Alive()

If you must force termination of a thread, use thread.join() would be the closes option, as this blocks the calling thread until the thread in question has finished.如果您必须强制终止线程,请使用 thread.join() 将是关闭选项,因为这会阻塞调用线程,直到相关线程完成。

Also refer to the docs for more info on the Threading functions另请参阅文档以获取有关线程功能的更多信息

https://docs.python.org/3/library/threading.html https://docs.python.org/3/library/threading.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM