Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Python Check if thread is alive

Note: the suggested answer doesn't work as I call the function every x seconds.

In python I have:

def inline_paid_generator(user_id, password):
    login_thread = threading.Thread(target=paid_generator, name="Register", args={user_id,password})
    login_thread.start()

How outside that function (from where I called it) how can I know if the thread is alive or not?

question from:https://stackoverflow.com/questions/65901896/python-check-if-thread-is-alive

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

1 Reply

0 votes
by (71.8m points)

You can set the thread as a global variable and only start it in the function, as following:

import time
import threading

def wait():
    time.sleep(5)

login_thread = threading.Thread(target=wait)

def start_inline_paid_generator():
    login_thread.start()

print(login_thread.is_alive()) # False

start_inline_paid_generator()

print(login_thread.is_alive()) # True

Then you can check anywhere in your program with login_thread.is_alive()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...