如何打破time.sleep()在python concurrent.futures [英] How to break time.sleep() in a python concurrent.futures

查看:217
本文介绍了如何打破time.sleep()在python concurrent.futures的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩 concurrent.futures

目前我的未来调用 time.sleep(secs)

a href =https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.cancel> Future.cancel()比我想象的少。

It seems that Future.cancel() does less than I thought.

如果未来已经执行, time.sleep()不会取消。

If the future is already executing, then time.sleep() does not get cancel by it.

的超时参数也一样wait()。它不会取消我的 time.sleep()

如何取消时间。

How to cancel time.sleep() which gets executed in a concurrent.futures?

为了测试,我使用ThreadPoolExecutor

推荐答案

如果你向 ThreadPoolExecutor 提交一个函数,执行器将在一个线程中运行该函数,并将其返回值存储在 Future object。由于并发线程的数量有限,您可以选择取消未来的执行,但是一旦工作线程中的控制被传递给可调用者,

If you submit a function to a ThreadPoolExecutor, the executor will run the function in a thread and store its return value in the Future object. Since the number of concurrent threads is limited, you have the option to cancel the pending execution of a future, but once control in the worker thread has been passed to the callable, there's no way to stop execution.

请考虑这个代码:

import concurrent.futures as f
import time

T = f.ThreadPoolExecutor(1) # Run at most one function concurrently
def block5():
    time.sleep(5)
    return 1
q = T.submit(block5)
m = T.submit(block5)

print q.cancel()  # Will fail, because q is already running
print m.cancel()  # Will work, because q is blocking the only thread, so m is still queued

一般来说,只要你想让某些内容可取消,你自己就有责任确保它是正确的。

In general, whenever you want to have something cancellable you yourself are responsible for making sure that it is.

现成的选项。 例如,请考虑使用 asyncio ,他们还有使用睡眠的示例。该概念通过以下方式规避问题:每当调用任何潜在的阻塞操作时,将控制返回到在最外层上下文中运行的控制循环,以及每当结果可用时应当继续执行的注释,或者 n 秒已过。

There are some off-the-shelf options available though. E.g., consider using asyncio, they also have an example using sleep. The concept circumvents the issue by, whenever any potentially blocking operation is to be called, instead returning control to a control loop running in the outer-most context, together with a note that execution should be continued whenever the result is available - or, in your case, after n seconds have passed.

这篇关于如何打破time.sleep()在python concurrent.futures的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆