Created
July 28, 2017 07:49
-
-
Save friek/c281741459ab44c4e3286d408ff07fc6 to your computer and use it in GitHub Desktop.
Demonstrates the use of futures in python 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from concurrent.futures import ThreadPoolExecutor | |
from time import sleep | |
executor = ThreadPoolExecutor(max_workers=10) | |
MAX_RUN_TIME = 4.5 | |
SLEEP_BETWEEN_WAITS = 0.1 | |
def return_slept(sleep_time): | |
sleep(sleep_time) | |
return sleep_time | |
def main(): | |
futures = [executor.submit(return_slept, 1.3), executor.submit(return_slept, 2.1)] | |
results = [] | |
futures_running = [] | |
time_slept = 0.0 | |
while time_slept < MAX_RUN_TIME: | |
futures_running.clear() | |
for future in futures: | |
if future.done(): | |
# Future is done, append the result. | |
results.append(future.result()) | |
else: | |
# The future is still running, so wait in the next loop | |
futures_running.append(future) | |
# If there are no more futures, stop the loop. | |
if len(futures_running) == 0: | |
break | |
# Otherwise, overwrite the futures list with the list of running futures | |
futures = futures_running.copy() | |
# And sleep for the maximum amount of time. | |
sleep(SLEEP_BETWEEN_WAITS) | |
time_slept += SLEEP_BETWEEN_WAITS | |
print("Completed after <= {0} seconds".format(time_slept)) | |
# Cancel the remaining futures. | |
for future in futures_running: | |
print("Cancelling future " + str(future)) | |
future.cancel() | |
print(str(results)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment