(十六)python之并发编程(协程)

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)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值