asyncio的结果不如预期

时间:2018-03-18 01:33:46

标签: python python-3.x asynchronous python-asyncio

我正在学习asyncio库以完成我想要实现的一些任务。我编写了以下代码来教自己如何能够在执行原始任务时切换到另一个任务。如下所示,summation()应该执行,直到满足条件,它应该跳转到secondaryTask()secondaryTask()完成后,它应该返回summation(),希望它完成。可能的结果应为sum=1225mul=24

import asyncio, time


async def summation():
    print('Running summation from 0 to 50:')
    sum = 0
    for i in range(25):
        sum = sum + i
        if i != 25:
            time.sleep(0.1)
        else:
            await asyncio.sleep(0) # pretend to be non-blocking work (Jump to the next task)
    print('This message is shown because summation() is completed! sum= %d' % sum)


async def secondaryTask():
    print('Do some secondaryTask here while summation() is on progress')
    mul = 1
    for i in range(1, 5):
        mul = mul * i
        time.sleep(0.1)
    await asyncio.sleep(0)
    print('This message is shown because secondaryTask() is completed! Mul= %d' % mul)

t0 = time.time()
ioloop = asyncio.get_event_loop()
tasks = [ioloop.create_task(summation()), ioloop.create_task(secondaryTask())]
wait_tasks = asyncio.wait(tasks)
ioloop.run_until_complete(wait_tasks)
ioloop.close()
t1 = time.time()
print('Total time= %.3f' % (t1-t0))

此代码未按预期执行,因为sum=300反对sum=1225。显然,summation()在处理secondaryTask()时不会继续。如何修改summation()以便能够对背景中剩余的25个值进行求和?

谢谢

1 个答案:

答案 0 :(得分:0)

这只是你的粗心。您希望从0到50运行summationsummation函数应为for i in range(50)