简体   繁体   中英

Python while loop with countdown and condition

I need to create while loop with condition that gets response from another thread but not wait for it too long. That's why I decide to use two conditions like

i = 0
while (not is_get_responce() and i<10000):
    i+=1
    time.sleep(1)

Is it a good practice?

let's avoid XYproblem

I have two threads and shared storage for this threads, all I need is to wait from the second thread while first thread did his job, after that, I get the result from the first thread and put it to my second thread. For sharing the result of jobs I used shared storage and function is_get_responce() return boolean if we have a response from the first thread.

I know that I can use .join() to wait for the first thread but I don't have a link from the second thread for it and it's not a good option for my case.

Assuming that is_get_responce() correctly configured, something like the following would make more sense to me:

start = time.time()
while time.time() - start < 10000:
    if is_get_responce():
        break
    time.sleep(1)

That being said, this could actually be an XY Problem ..

I don't know if this is possible in your case but the best practice is the following.

Use thread.join() method and specify a timeout.

This allow you to wait for a thread to finish until the optional timeout occurs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM