zoukankan      html  css  js  c++  java
  • asyncio执行阻塞代码

    在线程或者进程池中执行代码

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @time: 2021/12/31 2:41 下午
    # https://docs.python.org/zh-cn/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor
    import asyncio
    import concurrent.futures
    
    
    def blocking_io():
        # File operations (such as logging) can block the
        # event loop: run them in a thread pool.
        with open('/dev/urandom', 'rb') as f:
            return f.read(100)
    
    
    def cpu_bound():
        # CPU-bound operations will block the event loop:
        # in general it is preferable to run them in a
        # process pool.
        return sum(i * i for i in range(10 ** 7))
    
    
    async def main():
        loop = asyncio.get_running_loop()
    
        # 1. Run in the default loop's executor:
        result = await loop.run_in_executor(None, blocking_io)
        print('default thread pool', result)
    
        # 2. Run in a custom thread pool:
        with concurrent.futures.ThreadPoolExecutor() as pool:
            result = await loop.run_in_executor(pool, blocking_io)
            print('custom thread pool', result)
    
        # 3. Run in a custom process pool:
        with concurrent.futures.ProcessPoolExecutor() as pool:
            result = await loop.run_in_executor(pool, cpu_bound)
            print('custom process pool', result)
    
    
    if __name__ == '__main__':
        asyncio.run(main())
  • 相关阅读:
    数据库02
    MySQL1
    GIL 死锁 递归锁 event 信号量 线程Queue
    小脚本 暴力删除文件 刷屏
    常见web攻击 及基础 回顾(杂记)
    接口中的简单异步 async
    python协程 示例
    python 利用jinja2模板生成html
    python 调用webservices 接口
    python 进程 进程池 进程间通信
  • 原文地址:https://www.cnblogs.com/root0/p/15753108.html
Copyright © 2011-2022 走看看