Last active
August 29, 2015 14:07
-
-
Save podhmo/157307bc90edc35978ae to your computer and use it in GitHub Desktop.
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
# -*- coding:utf-8 -*- | |
import asyncio | |
from asyncio.futures import Future | |
from functools import partial | |
@asyncio.coroutine | |
def open_content(): | |
yield from asyncio.sleep(2) | |
print("[0] open") | |
@asyncio.coroutine | |
def push_content(): | |
yield from asyncio.sleep(0.5) | |
print("[1] push_content") | |
@asyncio.coroutine | |
def close_content(): | |
print("[2] close") | |
@asyncio.coroutine | |
def run(): | |
yield from open_content() | |
yield from push_content() | |
yield from close_content() | |
yield from asyncio.sleep(1) | |
loop.stop() | |
@asyncio.coroutine | |
def run_broken(): | |
asyncio.async(open_content()) | |
asyncio.async(push_content()) | |
asyncio.async(close_content()) | |
yield from asyncio.sleep(1) | |
loop.stop() | |
@asyncio.coroutine | |
def run_parallel(): | |
sentinel = Future(loop=loop) | |
tasks = [asyncio.async(open_content()), | |
asyncio.async(push_content()), | |
asyncio.async(close_content())] | |
results = [None] * len(tasks) | |
N = 0 | |
def _done_callback(i, f): | |
nonlocal N | |
results[i] = f._result | |
N += 1 | |
if N == len(tasks): | |
sentinel.set_result(results) | |
for i, t in enumerate(tasks): | |
t.add_done_callback(partial(_done_callback, i)) | |
yield from sentinel | |
loop.stop() | |
@asyncio.coroutine | |
def run_parallel2(): | |
yield from asyncio.gather(open_content(), | |
push_content(), | |
close_content()) | |
loop.stop() | |
loop = asyncio.get_event_loop() | |
asyncio.async(run_parallel2()) | |
loop.run_forever() | |
print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop)) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment