How to break time.sleep () in python concurrent.futures

I play with concurrent.futures .

My future is time.sleep(secs) calling time.sleep(secs) .

Future.cancel () seems to do less than I thought.

If the future is already running, then time.sleep() does not get canceled from it.

Same thing for the timeout parameter for wait () . It does not cancel my time.sleep() .

How to undo time.sleep() that runs in concurrent.futures?

For testing, I use ThreadPoolExecutor .

+6
source share
2 answers

If you send a function to ThreadPoolExecutor , the executor will run the function in the stream 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 the future, but once control in the workflow thread has been transferred to the callee, there is no way to stop execution.

Consider this code:

 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 cancel something, you are responsible for making sure that this is so.

However, there are some ready-made options. For example, consider using asyncio , they also have an example of using sleep . The concept bypasses the problem when any potential locking operation should be called, instead returning control to the control loop that works in the majority of the context, along with a note that execution should continue whenever the result is available, or, in your case, after n seconds.

+4
source

I don't know much about concurrent.futures, but you can use this logic to break time. Use a loop instead of sleep.time () or wait ()

 for i in range(sec): sleep(1) 

interrupt or break can be used to exit the loop.

+1
source

All Articles