Python:线程仍在运行 [英] Python: is thread still running

查看:144
本文介绍了Python:线程仍在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I see whether a thread has completed? I tried the following, but threads_list does not contain the thread that was started, even when I know the thread is still running.

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

推荐答案

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

The key is to start the thread using threading, not thread:

t1 = threading.Thread(target=my_function, args=())
t1.start()

然后使用

z = t1.isAlive()

l = threading.enumerate()

您还可以使用join():

You can also use join():

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

这篇关于Python:线程仍在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆