Is there a way to use asyncio.Queue in multiple threads?

前端 未结 4 1410
渐次进展
渐次进展 2020-12-05 11:36

Let\'s assume I have the following code:

import asyncio
import threading

queue = asyncio.Queue()

def threaded():
    import time
    while True:
        ti         


        
4条回答
  •  臣服心动
    2020-12-05 12:04

    BaseEventLoop.call_soon_threadsafe is at hand. See asyncio doc for detail.

    Simply change your threaded() like this:

    def threaded():
        import time
        while True:
            time.sleep(1)
            loop.call_soon_threadsafe(queue.put_nowait, time.time())
            loop.call_soon_threadsafe(lambda: print(queue.qsize()))
    

    Here's a sample output:

    0
    1443857763.3355968
    0
    1443857764.3368602
    0
    1443857765.338082
    0
    1443857766.3392274
    0
    1443857767.3403943
    

提交回复
热议问题