asyncio queue

from asyncio import Queue,sleep
import asyncio
from threading import Thread
import time

qu=Queue()
#put

async def putQ():
    global qu
    print('start put')
    i=1
    while True:
        print('put sleep')
        await sleep(1)
        print('put sleep')
        await qu.put(i)
        if i<=20:
            print('put',i)
        else:
            break
        i+=1

#get
async def getQ():
    global qu
    while True:
        await sleep(0.1)
        if qu.qsize() != 0:
            a= await qu.get()
            print('get',a)
        else:
            print('no get')

def start_loop(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()

new_loop=asyncio.new_event_loop()
t=Thread(target=start_loop,args=(new_loop,))
t.start()

# t1=asyncio.create_task(putQ())

taskput=asyncio.run_coroutine_threadsafe(putQ(),loop=new_loop)
taskget=asyncio.run_coroutine_threadsafe(getQ(),loop=new_loop)

while True:
    time.sleep(1)

 

from asyncio import Queue,sleep
import asyncio
from threading import Thread
import time

qu=Queue()
#put

async def putQ(qu):
    print('start put')
    i=1
    while True:
        print('put sleep')
        await sleep(1)
        print('put sleep')
        await qu.put(i)
        if i<=20:
            print('put',i)
        else:
            break
        i+=1

#get
async def getQ(qu):
    while True:
        await sleep(0.1)
        if qu.qsize() != 0:
            a= await qu.get()
            print('get',a)
        else:
            print('no get')

def start_loop(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()

new_loop=asyncio.new_event_loop()
t=Thread(target=start_loop,args=(new_loop,))
t.start()

# t1=asyncio.create_task(putQ())

taskput=asyncio.run_coroutine_threadsafe(putQ(qu),loop=new_loop)
taskget=asyncio.run_coroutine_threadsafe(getQ(qu),loop=new_loop)

while True:
    time.sleep(1)

  

 

原文地址:https://www.cnblogs.com/pythonClub/p/10107537.html