Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

multithreading - Python: is thread still running

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

Then use

z = t1.is_alive()
# Changed from t1.isAlive() based on comment. I guess it would depend on your version.

or

l = threading.enumerate()

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...