How to combine python asyncio with threads?

前端 未结 3 2007
死守一世寂寞
死守一世寂寞 2020-11-28 04:41

I have successfully built a RESTful microservice with Python asyncio and aiohttp that listens to a POST event to collect realtime events from various feeders.

It the

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 05:18

    Another alternative is to use loop.call_soon_threadsafe along with an asyncio.Queue as the intermediate channel of communication.

    The current documentation for Python 3 also has a section on Developing with asyncio - Concurrency and Multithreading:

    import asyncio
    
    # This method represents your blocking code
    def blocking(loop, queue):
        import time
        while True:
            loop.call_soon_threadsafe(queue.put_nowait, 'Blocking A')
            time.sleep(2)
            loop.call_soon_threadsafe(queue.put_nowait, 'Blocking B')
            time.sleep(2)
    
    # This method represents your async code
    async def nonblocking(queue):
        await asyncio.sleep(1)
        while True:
            queue.put_nowait('Non-blocking A')
            await asyncio.sleep(2)
            queue.put_nowait('Non-blocking B')
            await asyncio.sleep(2)
    
    # The main sets up the queue as the communication channel and synchronizes them
    async def main():
        queue = asyncio.Queue()
        loop = asyncio.get_running_loop()
    
        blocking_fut = loop.run_in_executor(None, blocking, loop, queue)
        nonblocking_task = loop.create_task(nonblocking(queue))
    
        running = True  # use whatever exit condition
        while running:
            # Get messages from both blocking and non-blocking in parallel
            message = await queue.get()
            # You could send any messages, and do anything you want with them
            print(message)
    
    asyncio.run(main())
    

    How to send asyncio tasks to loop running in other thread may also help you.

提交回复
热议问题