asyncio异步编程,给字典赋值,总是提示NoneType。
完整代码如下
import asyncio
import time
hs={}
def asy():
#asynchronous
start=time.perf_counter()
def fn(i):
hs[i]=i**9
async def fastdofn(i):
await fn(i)
tasks=[asyncio.ensure_future(fastdofn(i)) for i in range(10)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
print(hs)
print('runtime : {}'.format(time.perf_counter()-start))
asy()
运行结果:
{0: 0, 1: 1, 2: 512, 3: 19683, 4: 262144, 5: 1953125, 6: 10077696, 7: 40353607, 8: 134217728, 9: 387420489}
runtime : 0.049445499999999976
Task exception was never retrieved
future: <Task finished coro=<asy.<locals>.fastdofn() done, defined at C:\Users\QQ\Desktop\ls\py\异步.py:9> exception=TypeError("object NoneType can't be used in 'await' expression")>
Traceback (most recent call last):
File "C:\Users\QQ\Desktop\ls\py\异步.py", line 10, in fastdofn
await fn(i)
TypeError: object NoneType can't be used in 'await' expression
报错了10次
很奇怪的是,hs正常打印,而且达到了预期要求。为什么还会循环报错?
报错的问题解决了,但更懵了
import asyncio
import time
hs={}
def asy():
#asynchronous
start=time.process_time()
def fn(i):
hs[i]=i**9
async def fastdofn(i):
fn(i)
tasks=[asyncio.ensure_future(fastdofn(i)) for i in range(100000)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
print(hs[9])
ti=time.process_time()-start#time interval
print('asy runtime : {}'.format(ti))
return ti
def syn():
#synchronization
start=time.process_time()
def fn(i):
hs[i]=i**9
for i in range(100000):
fn(i)
print(hs[9])
ti=time.process_time()-start
print('syn runtime : {}'.format(ti))
return ti
def main():
l1=[]
l2=[]
for i in range(1,11):
print('{}th time'.format(i))
asy()
syn()
print('\n')
#print('asy is {} times faster than syn'.format(sum(l2)/sum(l1)))
main()
异步不应该比同步快么,怎么还慢了这么多?