异步阻塞
- 没有按照顺序等待结果,而是所有的任务都在异步执行着,但是我要等结果又不知道谁的结果先来,谁先结束我就先获取谁的结果
import requests
from multiprocessing import Process
from multiprocessing import Queue
url_lst=[
'https://www.cnblogs.com/Eva-J/articles/8253549.html',
'https://baidu.com'
]
def producer(i,url,q): #生产者
ret=requests.get(url)
q.put((i,ret.status_code))
if __name__ == '__main__':
q=Queue()
for index,url in enumerate(url_lst):
Process(target=producer,args=(index,url,q)).start()
for i in range(2): #没有按照顺序等待结果,而是所有的任务都在异步执行着,
# 但是我要等结果又不知道谁的结果先来,谁先结束我就先获取谁的结果
print(q.get())
import requests
from multiprocessing import Process
from multiprocessing import Queue
url_dic={
'bky':'https://www.cnblogs.com/Eva-J/articles/8253549.html',
'baidu':'https://baidu.com'
}
def producer(name,url,q): #生产者
ret=requests.get(url)
q.put((name,ret.text))
def consumer(q):
while True:
tup=q.get()
if tup==None:break
with open(f'{tup[0]}.html',encoding='utf-8',mode='w')as f:
f.write(tup[1])
if __name__ == '__main__':
q=Queue()
p1=[]
for key in url_dic:
p=Process(target=producer,args=(key,url_dic[key],q))
p.start()
p1.append(p)
Process(target=consumer,args=(q,)).start()
for p in p1:p.join()
q.put(None)