Last active
August 14, 2018 06:14
-
-
Save JustinSDK/639fc9712100097a8496fa6cbd887550 to your computer and use it in GitHub Desktop.
async_demo.py
This file contains 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 | |
import time | |
import random | |
def doAsync(task): | |
g = task() | |
future = next(g) | |
while True: | |
try: | |
future = g.send(future.result()) | |
g.send(future.result()) | |
except StopIteration: | |
break | |
def asyncFoo(n): | |
def process(n): | |
time.sleep(n) | |
return n * random.random() | |
with ThreadPoolExecutor(max_workers=4) as executor: | |
return executor.submit(process, n) | |
def asyncTasks(): | |
r1 = yield asyncFoo(1) | |
r2 = yield asyncFoo(r1) | |
r3 = yield asyncFoo(r2) | |
print(r3) | |
doAsync(asyncTasks) | |
def awaitThis(): | |
yield from asyncTasks() | |
yield from asyncTasks() | |
doAsync(awaitThis) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment