协程-单线程内的异步执行

1、仿协程实例

不同事件依次顺序执行

# coding=utf-8
import time


def calculate_1(step, event_name):
    for index in range(step):
        print('This is 【%s】 event 【%s】 step' % (event_name, index))
        time.sleep(0.1)


if __name__ == "__main__":
    start_time = time.time()
    calculate_1(7, 'play')
    calculate_1(3, 'sleep')
    calculate_1(10, 'eat')
    calculate_1(5, 'run')
    calculate_1(4, 'drank')
    print('const time is: %s' % (time.time() - start_time))  # const time is: 3.214914560317993

执行结果:

This is 【play】 event 【0】 step
This is 【play】 event 【1】 step
This is 【play】 event 【2】 step
This is 【play】 event 【3】 step
This is 【play】 event 【4】 step
This is 【play】 event 【5】 step
This is 【play】 event 【6】 step
This is 【sleep】 event 【0】 step
This is 【sleep】 event 【1】 step
This is 【sleep】 event 【2】 step
This is 【eat】 event 【0】 step
This is 【eat】 event 【1】 step
This is 【eat】 event 【2】 step
This is 【eat】 event 【3】 step
This is 【eat】 event 【4】 step
This is 【eat】 event 【5】 step
This is 【eat】 event 【6】 step
This is 【eat】 event 【7】 step
This is 【eat】 event 【8】 step
This is 【eat】 event 【9】 step
This is 【run】 event 【0】 step
This is 【run】 event 【1】 step
This is 【run】 event 【2】 step
This is 【run】 event 【3】 step
This is 【run】 event 【4】 step
This is 【drank】 event 【0】 step
This is 【drank】 event 【1】 step
This is 【drank】 event 【2】 step
This is 【drank】 event 【3】 step
const time is: 3.2026631832122803

不同事件仿照协程的执行逻辑

# coding=utf-8
"""
    1、事件循环
    2、I/O操作时能够跳出
"""
import time
import queue


def calculate_1(step, event_name):
    for index in range(step):
        print('This is 【%s】 event 【%s】 step' % (event_name, index))
        yield
        time.sleep(0.1)


if __name__ == "__main__":
    cal_1 = calculate_1(7, 'play')
    cal_2 = calculate_1(3, 'sleep')
    cal_3 = calculate_1(10, 'eat')
    cal_4 = calculate_1(5, 'run')
    cal_5 = calculate_1(4, 'drank')

    event_loop = queue.Queue()
    event_loop.put(cal_1)
    event_loop.put(cal_2)
    event_loop.put(cal_3)
    event_loop.put(cal_4)
    event_loop.put(cal_5)

    has_event = event_loop.get()

    num_event, num_event_end = 5, 0
    flag_event_add = True
    start_time = time.time()
    try:
        while has_event:

            try:
                result = next(has_event)
                flag_event_add = True
            except StopIteration as e:
                print('事件结束')
                num_event_end += 1
                flag_event_add = False
                if num_event_end >= num_event:
                    break

            next_has_event = event_loop.get(block=False)
            if flag_event_add:
                event_loop.put(has_event)
            else:
                event_loop.put(next_has_event)
            has_event = next_has_event
    except queue.Empty as e:
        print("queue.Empty exception")
    print('const time is: %s' % (time.time() - start_time))  # const time is: 3.076279401779175

执行结果:

This is 【play】 event 【0】 step
This is 【sleep】 event 【0】 step
This is 【eat】 event 【0】 step
This is 【run】 event 【0】 step
This is 【drank】 event 【0】 step
This is 【play】 event 【1】 step
This is 【sleep】 event 【1】 step
This is 【eat】 event 【1】 step
This is 【run】 event 【1】 step
This is 【drank】 event 【1】 step
This is 【play】 event 【2】 step
This is 【sleep】 event 【2】 step
This is 【eat】 event 【2】 step
This is 【run】 event 【2】 step
This is 【drank】 event 【2】 step
This is 【play】 event 【3】 step
事件结束
This is 【eat】 event 【3】 step
This is 【run】 event 【3】 step
This is 【drank】 event 【3】 step
This is 【play】 event 【4】 step
This is 【eat】 event 【4】 step
This is 【eat】 event 【5】 step
This is 【run】 event 【4】 step
事件结束
This is 【play】 event 【5】 step
This is 【eat】 event 【6】 step
This is 【eat】 event 【7】 step
事件结束
This is 【play】 event 【6】 step
事件结束
This is 【eat】 event 【8】 step
This is 【eat】 event 【9】 step
事件结束
const time is: 3.0819501876831055

2、协程相关概念

asyncio:内置对异步IO的支持

        event_loop事件循环:程序开启一个无限循环,通过将一些函数注册到事件循环上,当满足事件发生的时候,调用相应的协程函数

import asyncio


# python3.7以前的写法
loop = asyncio.get_event_loop()
print(loop)  # <ProactorEventLoop running=False closed=False debug=False>
loop.run_until_complete(asyncio.wait(task))

# python3.7之后的写法
asyncio.run(asyncio.wait(task))

        coroutine协程:协程对象,指一个使用async关键字定义的函数,它的调用不会立即执行函数,而是返回一个协程对象,协程对象需要注册到事件循环中,有事件循环调用

# 创建协程对象,并添加至列表
task = [coroutine_work_1(), coroutine_work_2()]

        task任务:一个协程对象就是一个原生可以挂起的函数,任务则是对协程进一步的封装,其中包含任务的各种状态

        future:代表将来执行或者没有执行的任务的结果,和task没有本质上的区别

        async关键字:async定义一个协程,

        await关键字:await用于挂起阻塞的异步调用接口,await可以获取到可等待对象的返回值,当事件循环遇到await关键字后会调度其他任务

# 协程任务
async def coroutine_work_1():
    for i in range(5):
        print('do something %s' % i)
        await asyncio.sleep(1)

代码:

# coding=utf-8
import asyncio


# 协程任务
async def coroutine_work_1():
    for i in range(5):
        print('do something %s' % i)
        await asyncio.sleep(1)


# 协程任务
async def coroutine_work_2():
    for i in range(3):
        print('do other thing %s' % i)
        await asyncio.sleep(1)


# 创建协程对象,并添加至列表
task = [coroutine_work_1(), coroutine_work_2()]

loop = asyncio.get_event_loop()
print(loop)  # <ProactorEventLoop running=False closed=False debug=False>
loop.run_until_complete(asyncio.wait(task))

执行结果:

<ProactorEventLoop running=False closed=False debug=False>
do other thing 0
do something 0
do other thing 1
do something 1
do other thing 2
do something 2
do something 3
do something 4

3、python3.7及以上的另一种协程写法

# coding=utf-8
import asyncio


async def coroutine_func():
    print('do coroutine task ...')


# python3.6版本
loop = asyncio.get_event_loop()
loop.run_until_complete(coroutine_func())  # coroutine_func()是一个协程对象


# python3.7以上版本
async def main():
    task = [
        asyncio.create_task(coroutine_func())
    ]
    await asyncio.wait(task)

asyncio.run(main())

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值