python线程多并发,是指在一个进程中开启n个线程,以此来达到并发执行任务。但是python中的线程有GIL解释锁,只能在同一时间运行一个线程。多线程的并发是多个线程来回切换去执行任务。线程少的话没什么影响,如果开的线程特别多,就会导致线程切换太耗费资源,达不到想要的多线程并发的效果。个人观点(python中的线程有点鸡肋)。
在这里还是要推荐下我自己建的Python开发学习群:628979297,群里都是学Python开发的,如果你正在学习Python ,小编欢迎你加入,大家都是软件开发党,不定期分享干货(只有Python软件开发相关的),包括我自己整理的一份2018最新的Python进阶资料和高级开发教程,欢迎进阶中和进想深入Python的小伙伴
下面就是我写的demo.爬虫用的,大家可以看看:
import asyncio
import aiohttp
import time
HEADERS = {
'User-Agent': "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
}
urls = 'https://sh.lianjia.com/ershoufang/pg{}/'
num = 100
async def get(url):
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=HEADERS) as response:
bytes = await response.read()
bytes = bytes.decode('utf-8') # 不能这么写 await response.read().bytes.decode('utf-8') 会报错 必须重新赋值 因为默认是协程的对象
print(bytes)
return
async def main():
url_list = [urls.format(i) for i in range(num)]
task = []
for url in url_list:
task.append(get(url))
await asyncio.gather(*task)
a = time.time()
new_loop = asyncio.new_event_loop()
new_loop.run_until_complete(main())
print(time.time() - a)