1、什么是协程?
2、greenlet
from greenlet import greenlet
import time
def test1():
for i in range(10):
print('test1----', i)
g2.switch()
time.sleep(0.1)
def test2():
for i in range(10):
print('test2----', i)
g1.switch()
time.sleep(0.1)
g3.switch()
def test3():
for i in range(10):
print('test3----', i)
g1.switch()
time.sleep(0.1)
g2.switch()
g1 = greenlet(test1)
g2 = greenlet(test2)
g3 = greenlet(test3)
# 切换到gr1中运行
g1.switch()
3、gevent模块(掌握)
import time
from gevent.monkey import patch_all
patch_all()
import gevent
import requests
def work1(name):
for i in range(10):
print('这个是work1', name)
# requests.get('http://www.baidu.com')
time.sleep(0.1)
def work2():
for i in range(10):
# requests.get('http://www.baidu.com')
print('这个是work2')
time.sleep(0.1)
g1 = gevent.spawn(work1, 'musen')
g2 = gevent.spawn(work2)
g1.join()
g2.join()
4、(扩展)原生协程的实现(异步编程)
import asyncio
# 协程函数定义
async def work():
for i in range(5):
print(i)
# 调用协程函数,返回的是一个协程对象
res = work()
print(res)
# 执行协程
asyncio.run(res)
# 打印结果
<coroutine object work at 0x7f929a49e840>
0
1
2
3
什么是事件循环?
5、通过原生的协程函数实现多任务
import asyncio
async def work1():
for i in range(5):
await asyncio.sleep(1)
print("work1-打孔--{}".format(i))
async def work2():
for i in range(6):
await asyncio.sleep(1)
print("work2--浇花-{}".format(i))
async def main():
task1 = asyncio.create_task(work1())
task2 = asyncio.create_task(work2())
task3 = asyncio.create_task(work2())
await task1
await task2
await task3
asyncio.run(main())
6、异步请求库
import time
import aiohttp
import asyncio
async def get_page(urls):
async with aiohttp.ClientSession() as session:
while urls:
url = urls.pop()
await asyncio.sleep(0.2)
# async with session.get(url) as response:
# # print(f"第------次请求请求:", url)
# await response.read()
async def main():
urls = ["http://test.baidu.com/" for i in range(100000)]
tasks = []
for i in range(10000):
tasks.append(get_page(urls))
await asyncio.gather(*tasks)
if __name__ == '__main__':
s_time = time.time()
res = asyncio.run(main())
e_time = time.time()
print("时间:", e_time - s_time)