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
149 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 Answer

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()


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

...