How can I wrap a synchronous function in an async coroutine?

后端 未结 4 599
南笙
南笙 2021-01-30 08:28

I\'m using aiohttp to build an API server that sends TCP requests off to a seperate server. The module that sends the TCP requests is synchronous and a black box for my purposes

4条回答
  •  粉色の甜心
    2021-01-30 09:31

    Maybe someone will need my solution to this problem. I wrote my own library to solve this, which allows you to make any function asynchronous using a decorator.

    To install the library, run this command:

    $ pip install awaits
    

    To make any of your functions asynchronous, just add the @awaitable decorator to it, like this:

    import time
    import asyncio
    from awaits.awaitable import awaitable
    
    @awaitable
    def sum(a, b):
      # heavy load simulation
      time.sleep(10)
      return a + b
    

    Now you can make sure that your function is really asynchronous coroutine:

    print(asyncio.run(sum(2, 2)))
    

    "Under the hood" your function will be executed in the thread pool. This thread pool will not be recreated every time your function is called. A thread pool is created once and accepts new tasks via a queue. This will make your program run faster than using other solutions, because the creation of additional threads is an additional overhead.

提交回复
热议问题