在不丢失数据的情况下取消异步

时间:2018-01-22 09:49:19

标签: python python-asyncio

我有这个循环:

tasks = [self.frontend_wrap(),
                         self.server_wrap()]
completed, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for i in pending:
       i.cancel()
for done in completed:
    do staff

换句话说,我正在等待一个任务完成,并开始处理它。由于错误“已经等待的任务”,我取消了前一个,我不能再重复使用了。问题是,然后我取消了我的任务,我正在丢失数据。当任务“同时”完成时,就会发生这种情况。那么如何保存所有数据?

1 个答案:

答案 0 :(得分:0)

使用asyncio.Event代替取消任务,允许他们自行退出:

import asyncio

import random

done = asyncio.Event()


async def foo():
    while not done.is_set():
        print("foo")
        await asyncio.sleep(random.uniform(0.1, 0.4))
        if random.randint(1, 15) == 1:
            break

    print("foo done")
    done.set()


async def bar():
    while not done.is_set():
        print("bar")
        await asyncio.sleep(random.uniform(0.1, 0.4))
        if random.randint(1, 15) == 1:
            break

    print("bar done")
    done.set()


async def main():
    await asyncio.wait([foo(), bar()])
    # do stuff


asyncio.get_event_loop().run_until_complete(main())