异步编程二


"""定义协程"""
now = lambda: time.time()


async def do_some_work(x):
    print('Waiting', x)


start = now()

coroutine = do_some_work(2)
loop = asyncio.get_event_loop()
loop.run_until_complete(coroutine)
print('time:', now() - start)
"""
通过async关键字定义一个协程(coroutine),
协程也是一种对象。协程不能直接运行,
需要把协程加入到事件循环(loop),
由后者在适当的时候调用协程。
asyncio.get_event_loop方法可以创建一个事件循环,
然后使用run_until_complete将协程注册到事件循环,
并启动事件循环
"""

"""创建task"""
now = lambda: time.time()


async def do_some_work(x):
    print('Waiting', x)


start = now()

coroutine = do_some_work(2)
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(coroutine)
# task = loop.create_task(coroutine)
print(task)
loop.run_until_complete(task)
print(task)
print('time:', now() - start)

"""
协程对象不能直接运行,在注册事件循环的时候,
其实是run_until_complete方法将协程包装成为了一个任务(task)对象。
所谓task对象是Future类的子类。保存了协程运行后的状态,
用于未来获取协程的结果。

创建task后,task在加入事件循环之前是pending状态,
因为do_some_work中没有耗时的阻塞操作,task很快就执行完毕了。
后面打印的finished状态。

asyncio.ensure_future(coroutine) 和 loop.create_task(coroutine)
都可以创建一个task,run_until_complete的参数是一个futrue对象。
当传入一个协程,其内部会自动封装成task,task是Future的子类。
isinstance(task, asyncio.Future)将会输出True。
"""

"""绑定回调"""
now = lambda: time.time()


async def do_some_work(x):
    print('Waiting', x)
    return f'Done affter{x}s '


def callback(t, future):
    print('callback:', future.result(), t)


start = now()

coroutine = do_some_work(2)
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(coroutine)
task.add_done_callback(functools.partial(callback, 2))
loop.run_until_complete(task)

print('time:', now() - start)

"""
绑定回调,在task执行完毕的时候可以获取执行的结果,
回调的最后一个参数是future对象,通过该对象可以获取协程返回值。
如果回调需要多个参数,可以通过偏函数导入。

可以看到,coroutine执行结束时候会调用回调函数。
并通过参数future获取协程执行的结果。
我们创建的task和回调里的future对象,实际上是同一个对象。

"""

"""future 与 result"""
now = lambda: time.time()


async def do_some_work(x):
    print(f'Waiting{x}')
    return f'done affter{x}s'


start = now()

loop = asyncio.get_event_loop()
coroutine = do_some_work(2)
task = asyncio.ensure_future(coroutine)
loop.run_until_complete(task)
print(task.result())
print(f'Time:{now()-start}')

"""task有fiinished状态。在那个时候,可以直接读取task的result方法。"""

"""阻塞和await"""
now = lambda: time.time()


async def do_some_work(x):
    print(f'Waiting{x}')
    await asyncio.sleep(1)
    return f'done affter{x}s'


start = now()

loop = asyncio.get_event_loop()
coroutine = do_some_work(2)
task = asyncio.ensure_future(coroutine)
loop.run_until_complete(task)
print(task.result())
print(f'Time:{now()-start}')

"""
耗时的操作一般是一些IO操作,例如网络请求,文件读取等。
我们使用asyncio.sleep函数来模拟IO操作。
协程的目的也是让这些IO操作异步化。
"""

"""异步"""

now = lambda: time.time()


async def do_some_work(x):
    print(f'waiting{x}')
    await asyncio.sleep(3)
    return f'done{x}s'


start = now()


async def res():
    """方法一"""
    tasks = [asyncio.ensure_future(do_some_work(x)) for x in range(5)]
    r = await  asyncio.gather(*tasks)
    print(asyncio.Task.all_tasks()) # 查看task
    for i in r:
        print(i)

# """方法二"""
# tasks = [do_some_work(x) for x in range(5)]
# dones, paedings = await asyncio.wait(tasks)
# for i in dones:
#     print(i.result())
# """方法三"""
# tasks = [do_some_work(x) for x in range(5) ]
# for i in as_completed(tasks):
#     res = await i
#     print(res)

loop = asyncio.get_event_loop()
loop.run_until_complete(res())
# loop.stop()
# loop.run_forever()
print(now() - start)

"""不同线程事件循环"""
now = lambda: time.time()


def new_loop_fun(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()


def work(x):
    time.sleep(x)
    print('test...')


start = now()

new_loop = asyncio.new_event_loop()
t = Thread(target=new_loop_fun, args=(new_loop,))
t.start()
new_loop.call_soon_threadsafe(work, 1)
new_loop.call_soon_threadsafe(work, 2)
print(now() - start)

"""新线程协程"""

now = lambda: time.time()


def new_loop_fun(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()


async def work(x):
    time.sleep(x)
    print('test...')


start = now()

new_loop = asyncio.new_event_loop()
t = Thread(target=new_loop_fun, args=(new_loop,))
# t.setDaemon(Thread) 设置守护线程
t.start()
asyncio.run_coroutine_threadsafe(work(2), new_loop)
asyncio.run_coroutine_threadsafe(work(3), new_loop)
print(now() - start)

</pre>
<pre>def a(loop):
    print('test')
    loop.stop()


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.call_soon(a, loop)  # 立即执行
    loop.run_forever()

    loop.call_later(2, a, loop)  # 稍后执行
    loop.run_forever()
    
    loop.call_at(loop.time()+3, a, loop)  # 定时执行
    loop.run_forever()
    
    loop.close()</pre>
<pre>

最后更新于:2018-07-20 13:48:04