asyncio 初体验

First experience with asyncio

我正在学习python-asyncio,我正在尝试编写一个简单的模型。

我有一个函数处理任务。在处理时,它会转到另一个远程服务获取数据,然后打印一条消息。

我的代码:

dd = 0

@asyncio.coroutine
def slow_operation():
    global dd
    dd += 1
    print('Future is started!', dd)
    yield from asyncio.sleep(10 - dd)  # request to another server
    print('Future is done!', dd)

def add():
    while True:
        time.sleep(1)
        asyncio.ensure_future(slow_operation(), loop=loop)

loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.ensure_future(slow_operation(), loop=loop)
th.Thread(target=add).start()
loop.run_forever()

但是这段代码在睡觉时不会切换上下文:

yield from asyncio.sleep(10 - dd)

我该如何解决?

asyncio.ensure_future is not thread-safe, that's why slow_operation tasks are not started when they should be. Use loop.call_soon_threadsafe:

    callback = lambda: asyncio.ensure_future(slow_operation(), loop=loop)
    loop.call_soon_threadsafe(cb)

或者 asyncio.run_coroutine_threadsafe 如果你是 运行宁 python 3.5.1:

    asyncio.run_coroutine_threadsafe(slow_operation(), loop)

但是,您可能应该将线程的使用保持在最低限度。除非你在自己的线程中使用库 运行ning 任务,否则所有代码都应该 运行 在事件循环内(或在执行程序内,参见 loop.run_in_executor)。