今天发现一个python使用起来比较简单的多线程库,分享一下。
总所周知,python的GIL限制了python无法使用真正的多线程,要想做IO异步任务,个人更推荐使用协程。
import requests
import time
# 线程池
from multiprocessing.dummy import Pool
def get_requets(url):
# html = requests.get(url=url).text
time.sleep(2)
print(123)
if __name__ == ‘__main__‘:
start = time.time()
url_ls = [
‘http://www.baidu.com‘,
‘http://www.baidu.com‘,
‘http://www.baidu.com‘
]
# 同步代码
# for url in url_ls:
# get_requets(url)
# print(‘总耗时: ‘, time.time()-start)
# 线程池异步代码
pool = Pool(3)
pool.map(get_requets, url_ls)
pool.close() #闭pool,使其不在接受新的(主进程)任务
pool.join() #主进程阻塞后,让子进程继续运行完成,子进程运行完后,再把主进程全部关掉。
print(‘总耗时: ‘, time.time() - start)
原文:https://www.cnblogs.com/hehahahepython/p/15131704.html