【问题标题】:Asyncio or Concurrent in pythonpython中的异步或并发
【发布时间】:2021-04-04 10:58:03
【问题描述】:

我想同时做两个功能 那个末端是相互关联的 例如:

def func1 ():
    while True:
        print('it fine')

这只是为了美观,并没有什么特别的。

但是下一个函数扮演程序的主要角色,我希望 func1 一直运行到它完成。

def func2():
    number=1000
    for i in range(number):
        if i % 541 ==0:
            print('Horay !!!')
            return

好吧,这里有两个问题,一个是我该怎么做,二是我可以离开 func1 吗?

我需要这样的输出:

it fine
it fine
it fine
it fine
it fine
it fine
it fine
it fine
it fine
Horay !!!

但我想准确地使用两个函数。

【问题讨论】:

    标签: python loops concurrency async-await python-asyncio


    【解决方案1】:

    我已经使用 asyncio 重写了您的示例。注意几点:

    • 使用async def 声明
    • 并发协程由create_task()启动
    • 协程应至少使用一个await 调用,以允许并发协程协同执行。 (关注await asyncio.sleep()

    如需更深入的了解,请参阅此postofficial documentation

    import asyncio
    
    
    async def func1():
        while True:
            print('it fine')
            await asyncio.sleep(0)
    
    
    async def func2():
        number = 1000
        task = asyncio.create_task(func1())  # run concurrent task
        for i in range(1, number):
            if i % 541 == 0:
                print('Horay !!!')
                task.cancel()  # stop task
                return
            await asyncio.sleep(0)
    
    asyncio.run(func2())  # run program entrypoint coroutine
    
    ...
    it fine
    it fine
    it fine
    it fine
    it fine
    it fine
    Horay !!!
    

    【讨论】:

    • 哇哦它的工作正确,但我不能完全理解它,你能告诉我你在哪里学到的,另外建议一个好的来源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多