asyncio 的结果不符合预期
Results of asyncio are not as expected
我正在学习 asyncio
库来完成一些我想完成的任务。我编写了以下代码来自学如何在执行原始任务时切换到另一个任务。正如您在下面看到的,应该执行 summation()
,直到满足跳转到 secondaryTask()
的条件。 secondaryTask()
完成后,它应该 return 回到 summation()
,希望它能完成。潜在结果应该是 sum=1225
和 mul=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
相反。显然,在处理 secondaryTask()
时,summation()
不会继续。如何修改summation()
才能在后台对剩余的25个值进行求和?
谢谢
只是你粗心大意。你想 运行 summation
从 0 到 50,你的 summation
函数应该是 for i in range(50)
我正在学习 asyncio
库来完成一些我想完成的任务。我编写了以下代码来自学如何在执行原始任务时切换到另一个任务。正如您在下面看到的,应该执行 summation()
,直到满足跳转到 secondaryTask()
的条件。 secondaryTask()
完成后,它应该 return 回到 summation()
,希望它能完成。潜在结果应该是 sum=1225
和 mul=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
相反。显然,在处理 secondaryTask()
时,summation()
不会继续。如何修改summation()
才能在后台对剩余的25个值进行求和?
谢谢
只是你粗心大意。你想 运行 summation
从 0 到 50,你的 summation
函数应该是 for i in range(50)