简体   繁体   English

Python while循环与倒数和条件

[英]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 让我们避免XY问题

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. 为了共享作业的结果,如果使用第一个线程的响应,则使用共享存储和函数is_get_responce()返回布尔值。

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. 我知道我可以使用.join()等待第一个线程,但是我没有第二个线程的链接,这对我来说不是一个好选择。

Assuming that is_get_responce() correctly configured, something like the following would make more sense to me: 假设is_get_responce()配置正确,对我来说,以下内容将更有意义:

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 .. 话虽如此,这实际上可能是XY问题 ..

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. 使用thread.join()方法并指定超时。

This allow you to wait for a thread to finish until the optional timeout occurs. 这使您可以等待线程完成,直到发生可选超时为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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