1.什么是异步与异步的好处在哪里:异步不会阻塞主进程、主线程的执行。
2.异步和多线程和多进程的区别:1.异步也是一种线程,是一种轻量级的线程,python中称为携程。(与C++11 多线程类似) 2. 异步可以获取函数的返回值,而多线程多进程不能获取返回值,如果想获取返回值必须采用进程池或线程池。3.主进程需要异步才行。4.异步更适合文件读写使用
3.async,await与asyncio 模块
不采用异步:
#coding:utf-8
import time
import os
import multiprocessing
import json
import random
import threading
from concurrent.futures import ThreadPoolExecutor
def a():
for i in range(10):
print(i,'a')
time.sleep(random.random()*2)
return 'a function'
def b():
for i in range(10):
print(i,'b')
time.sleep(random.random()*2)
return 'b function'
if __name__ == '__main__':
start = time.time()
a()
b()
print('执行时间:',time.time()-start) #19.524394035339355
采用异步的方式:
#coding:utf-8
import time
import os
import multiprocessing
import json
import random
import threading
import asyncio
from concurrent.futures import ThreadPoolExecutor
async def a():
for i in range(10):
print(i,'a','a()进程号:',os.getpid())
#time.sleep(random.random()*2) #time.sleep(...) 是一个CPU级别的阻塞,是一个同步的任务阻塞,必须修改成异步的,才有异步效果。
await asyncio.sleep(random.random() * 2)
return 'a function'
async def b():
for i in range(10):
print(i,'b','b()进程号:',os.getpid())
#time.sleep(random.random()*2)
await asyncio.sleep(random.random() * 2)
return 'b function'
async def main():
result = await asyncio.gather(
a(),
b()
)
print(result)
if __name__ == '__main__':
start = time.time()
#a()
#b()
asyncio.run(main())
print('执行时间:',time.time()-start) #9.962631940841675
print('parent is %s '% os.getpid())
4.gevent异步模块的使用
pip install gevent
#coding:utf-8
import time
import os
import multiprocessing
import json
import random
import threading
import asyncio
import gevent
from concurrent.futures import ThreadPoolExecutor
def gevent_a():
for i in range(10):
print(i,'a gevent pid:',os.getpid())
gevent.sleep(random.random()*2) # 这里的sleep与time.time()的区别。这里的gevent.sleep(...)是当前业务的阻塞。time.time()是CPU级别的阻塞。
return 'gevent a result'
def gevent_b():
for i in range(10):
print(i,'b gevent pid:',os.getpid())
gevent.sleep(random.random()*2)
return 'gevent b result'
if __name__ == '__main__':
start = time.time()
g_a = gevent.spawn(gevent_a)
g_b = gevent.spawn(gevent_b)
g_a.start()
g_b.start()
gevent_list = [g_a,g_b]
result = gevent.joinall(gevent_list)
print(result) # 返回2个携程对象
print(dir(result[0])) #查看携程对象里面有哪些函数?
print(result[0].value) #返回携程函数的返回值
print(result[1].value) # 返回携程函数的返回值
print('执行时间:',time.time()-start) #9.962631940841675
print('parent is %s '% os.getpid())