栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python asyncio的基本使用和搭配多线程

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python asyncio的基本使用和搭配多线程

基本使用
  • async 包装函数创建一个协程
  • await 可以针对耗时的操作进行挂起,类似yield,函数让出控制权
import asyncio
import time

from pprint import pprint

async def print_myself(name, slp):
    print(f'My name is {name}')
    await asyncio.sleep(slp)
    return f"{name}函数已执行完毕"

def callback(future):
    print("Callback: ", future.result())

coroutine1 = print_myself("cxs", 1)
coroutine2 = print_myself("cxw", 2)
coroutine3 = print_myself("clw", 3)

# 创建一个事件循环
loop = asyncio.get_event_loop()

"""
两种方式创建 future对象
"""
task = loop.create_task(coroutine)
# 或者
task = asyncio.ensure_future(coroutine)
tasks = [
    asyncio.ensure_future(coroutine1),
    asyncio.ensure_future(coroutine2),
    asyncio.ensure_future(coroutine3),
]

# 判断类型
print(isinstance(tasks, asyncio.Future))

# 绑定回调函数,获取task返回值
task.add_done_callback(callback)  

# 将协程注册进事件循环
loop.run_until_complete(asyncio.wait(tasks))  
# 或者
loop.run_until_complete(asyncio.gather(*tasks))

loop.close()
配合多线程
import time
import asyncio

from threading import Thread, current_thread


def start_loop(loop):
    """
    开启一个无限事件循环
    """
    asyncio.set_event_loop(loop)
    loop.run_forever()


def get_thread_name():
    print("current thread name: ", current_thread())


async def coroutine_work(x):
    """
    协程
    """
    get_thread_name()
    print("start: ", int(time.time()))
    await asyncio.sleep(x)
    end = time.time()
    print(f"end: ", int(time.time()))


def common_work(x):
    """
    普通函数
    """
    get_thread_name()
    start = time.time()
    time.sleep(x)
    end = time.time()
    print(f"耗时{end - start}")


def main():
    """
    主线程
    """
    get_thread_name()
    loop = asyncio.new_event_loop()
    t = Thread(target=start_loop, args=(loop,))  # 子线程
    t.start()

    # 协程注册到事件循环
    asyncio.run_coroutine_threadsafe(coroutine_work(4), loop)
    asyncio.run_coroutine_threadsafe(coroutine_work(2), loop)


main()

'''
输出如下:

current thread name:  <_MainThread(MainThread, started 36316)>
current thread name:  
start:  1654077800
current thread name:  
start:  1654077800
end:  1654077802
end:  1654077804
'''

从输出结果可以得出:

  • 两个协程都是在子线程中运行,区别于主线程
  • 两个协程是同时启动,并发运行的
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/942457.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号