首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在dict中管理异步协同

在dict中管理异步协同
EN

Stack Overflow用户
提问于 2020-01-21 13:41:06
回答 1查看 782关注 0票数 1

我想在一个数据库中管理一些协同线,同时运行一个主协同线。具体来说,我想启动无止境的协同,将它们的处理程序放在一个dict中,然后再通过dict调用取消它们。在我的示例中,我想启动4个协同器,它们将使用协同线doomsday逐个取消。我正在使用Python3.6。

代码语言:javascript
复制
import asyncio
import traceback


async def add_to_handler(node, func):
    func_handler[node] = asyncio.ensure_future(func, loop=loop)
    return

async def test_func1():
    while True:
        print("1 - HeNlO")
        await asyncio.sleep(1)

async def test_func2():
    while True:
        print("2 - TestFunc2")
        await asyncio.sleep(2)


async def test_func3():
    while True:
        print("3 - Tukan")
        await asyncio.sleep(3)


async def test_func4():
    while True:
        print("4 - Do Coro!")
        await asyncio.sleep(4)


async def doomsday():
    # Cancel coroutine every 10 seconds
    print("launch doomsday")
    for i in range(len(func_handler)):
        await asyncio.sleep(10)
        print("start cancelling with {}".format(i))
        func_handler[str(i + 1)].cancel()
    return

async def main():
    await add_to_handler("1", test_func1)
    await add_to_handler("2", test_func2)
    await add_to_handler("3", test_func3)
    await add_to_handler("4", test_func4)
    await doomsday()
    while True:
        print("z..z..Z..Z...Z")
        print(func_handler)
        await asyncio.sleep(5)

func_handler = {}

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(main())
except KeyboardInterrupt:
    print("stop loop")
    loop.close()

我尝试了使用.call_later方法AbstractEventLoop,而不是一个没完没了的with循环,但是它仍然不想工作,而且似乎,我的协同机制被看作是函数,但我不知道为什么。我的错在哪里?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-21 14:00:08

尝试更改此功能:

代码语言:javascript
复制
async def add_to_handler(node, func):
    func_handler[node] = asyncio.ensure_future(func(), loop=loop)
    return None

关注asyncio.ensure_future(func(),loop=loop)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59842449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档