Python:线程仍在运行

use*_*003 12 python multithreading

如何查看线程是否已完成?我尝试了以下内容,但threads_list不包含已启动的线程,即使我知道该线程仍在运行.

import thread
import threading

id1 = thread.start_new_thread(my_function, ())
#wait some time
threads_list = threading.enumerate()
# Want to know if my_function() that was called by thread id1 has returned 

def my_function()
    #do stuff
    return
Run Code Online (Sandbox Code Playgroud)

use*_*003 24

关键是使用线程启动线程,而不是线程:

t1 = threading.Thread(target=my_function, args=())
t1.start()
Run Code Online (Sandbox Code Playgroud)

然后用

z = t1.isAlive()
Run Code Online (Sandbox Code Playgroud)

要么

l = threading.enumerate()
Run Code Online (Sandbox Code Playgroud)

您还可以使用join():

t1 = threading.Thread(target=my_function, args=())
t1.start()
t1.join()
# Will only get to here once t1 has returned.
Run Code Online (Sandbox Code Playgroud)

  • 只是一个**建议**:请记住,如果您尚未调用“start”,“is_alive”也会返回 True。如果你的程序很复杂并且有任何条件可以启动你的威胁,你可以将程序置于死锁状态。 (3认同)
  • 2019年答案:使用`is_alive`代替`isAlive`; 您将看到上述答案的弃用警告。 (2认同)