python 中是否有 threading.Condition 变量的替代方案可以更好地支持超时而无需轮询?
我在需要超时的线程中使用条件变量。直到我看到运行大量线程时的 CPU 使用情况时,我才注意到线程模块中提供的条件变量实际上并没有休眠,而是在提供超时作为参数时进行轮询。
有没有一种替代方案可以像 pthreads 一样休眠?
让大量线程以多秒的时间间隔休眠,却仍然占用 CPU 时间,这似乎很痛苦。
谢谢!
I'm using condition variables in threads that require a timeout. I didn't notice until I saw the CPU usage when having a lot of threads running, that the condition variable provided in the threading module doesn't actually sleep, but polls when a timeout is provided as an argument.
Is there an alternative to this that actually sleeps like pthreads?
Seems painful to have a lot of threads sleeping at multiple second intervals only to have it still eating CPU time.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Python 中这似乎很难做到,但这里有一个解决方案。它依赖于生成额外的线程,但不使用轮询,并确保一旦超时到期或原始 wait() 返回后,原始线程就会被唤醒。
注意:以下代码包含一个测试用例,该测试用例测试由于超时以及由于通知而导致的条件等待结束。
This seems tricky to do in Python, but here is a one solution. It relies on spawning additional threads but doesn't use polling AND ensures that the original thread is woken up as soon as the timeout expires or as soon as the original wait() returns.
Note: The following code includes a test case which tests both the conditional wait ending due to a timeout as well as due to a notification.
我对Python不熟悉,但如果你能够阻塞条件变量(没有超时),你可以自己实现超时。让阻塞线程存储它开始阻塞的时间,并设置一个计时器来向它发出信号。当它醒来时,检查超时时间。这不是一个很好的方法,除非您可以将计时器聚合到单个线程,否则,您的线程计数将无缘无故地增加一倍。
I'm not familiar with Python, but if you are able to block on a condition variable (without a timeout), you could implement the timeout yourself. Let the blocking thread store the time it began blocking and set a timer to signal it. When it wakes, check the time elapsed for a timeout. This isn't a very good way to do it unless you can aggregate the timers to a single thread, otherwise, your thread count would double without reason.