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
173 views
in Technique[技术] by (71.8m points)

python 3.x - python3 - thread is missing from enumerate result when it is sleeping

We have an API endpoint that starts a thread, and another endpoint to check the status of the thread (based on a thread ID returned by the first API call). We use the threading module.

The function that the thread is executing may or may not sleep for a duration of time.

When we create the thread, we override the default name provided by the module and add the thread ID that was generated by us (so we can keep track).

The status endpoint gets the thread ID from the client request and simply loops over the results from threading.enumerate(). When the thread is running and not sleeping, we see that the thread is returned by the threading.enumerate() function. When it is sleeping, it is not.

The function we use to see if a thread is alive:

def thread_is_running(thread_id):
    all_threads = [ t.getName() for t in threading.enumerate() ]
    return any(thread_id in item for item in all_threads)

When we run in debug and print the value of "all_threads", we only see the MainThread thread during our thread's sleep time. As soon as the sleep is over, we see our thread in the value of "all_threads".

This is how we start the thread:

thread_id = random.randint(10000, 50000)
thread_name = f"{service_name}-{thread_id}"
threading.Thread(target=drain, args=(service_name, params,), name=thread_name).start()

Is there a way to get a list of all threads including idle threads? Is a sleeping thread marked as idle? Is there a better way to pause a thread?

We thought about making the thread update it's state in a database, but due to some internal issue we currently have, we cannot 100% count on writing to our database, so we prefer checking the system for the thread's status.

question from:https://stackoverflow.com/questions/65871190/python3-thread-is-missing-from-enumerate-result-when-it-is-sleeping

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

1 Reply

0 votes
by (71.8m points)
Waitting for answers

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

...