
说明
1、当一个异步过程调用发出后,调用者不会立刻得到结果。
实际处理这个调用的部件是在调用发出后,通过状态、通知来通知调用者,或通过回调函数处理这个调用。
2、非阻塞的意思是,不能立刻得到结果之前,该函数不会阻塞当前线程,而会立刻返回。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | from time import time, sleep
"" "
同步操作
" ""
def app01():
def fn1():
sleep(3)
print( "fn1 ..." )
def fn2():
sleep(2)
print( "fn2 ..." )
def fn3():
sleep(5)
print( "fn3 ..." )
fn1()
fn2()
fn3()
"" "
asyncio
" ""
def app02():
import asyncio
async def fn1():
await asyncio.sleep(3)
print( "fn1 ..." )
async def fn2():
await asyncio.sleep(2)
print( "fn2 ..." )
async def fn3():
await asyncio.sleep(5)
print( "fn3 ..." )
loop = asyncio.get_event_loop()
tasks = [
fn1(),
fn2(),
fn3()
]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
if __name__ == '__main__' :
startTime = time()
# app01()
app02()
endTime = time()
print( '花费了' , str(endTime - startTime), '秒' )
# 第一个 10s
# 第二个 5s
|
以上就是python中异步非阻塞的实现,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。