python asyncio 执行非协程函数

import asyncio
import time
from concurrent.futures.thread import ThreadPoolExecutor
def commonmethod(value):
    print(value)
    time.sleep(2)
    print('done')
    return "it is ok"


async def main(value):
     # 获取当前正在执行的事件循环
    loop = asyncio.get_running_loop()
    # 使用run_in_executor 执行非协程函数

    # 第一步是调用ThreadPoolExecutor的submit方法,去线程池中申请一个线程执行commonmethod方法,并返回一个concurrent.futures.Future对象
    # 第二步 调用asyncio.wrap_future将concurrent.futures.Future转换成asyncio.Feture
    # 第一个参数为None,默认使用线程池
    # result = loop.run_in_executor(None,commonmethod,value)
    # response = await result
    # print(response)

    # 显示的声明线程池
    with ThreadPoolExecutor(max_workers=10) as worker:
        result = loop.run_in_executor(worker,commonmethod,value)
        response = await result
        print(response)

# 将协程对象添加到事件循环中,并运行
tasks=[main(i) for i in range(5)]

# 可以wait的对象包括:协程对象,task
# asyncio.run会创建一个事件循环,并将携程对象加入到事件循环
asyncio.run(asyncio.wait(tasks))

future

import asyncio

async def test(fu):
    print(1)
    await asyncio.sleep(2)
    fu.set_result(666)

async def main():
    # 获取当前正在执行的事件循环
    loop = asyncio.get_running_loop()

    fu = loop.create_future()
    # 创建task对象,加入到事件循环中
    task= asyncio.create_task(test(fu))

    await task

    # 等待返回值
    response = await fu

    print(response)

asyncio.run(main())
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值