Python asyncio 基本使用、搭配多线程

本文介绍了如何使用asyncio库在Python中创建协程,通过await关键字实现任务挂起,并展示了在多线程环境下协程的并发执行。实例演示了协程在子线程中的应用和异步回调的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本使用
  • 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:  <Thread(Thread-1, started 4136)>
start:  1654077800
current thread name:  <Thread(Thread-1, started 4136)>
start:  1654077800
end:  1654077802
end:  1654077804
'''

从输出结果可以得出:

  • 两个协程都是在子线程中运行,区别于主线程
  • 两个协程是同时启动,并发运行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值