import asyncio
import threading
async def asyncio_loop():
i = 1
while True:
i = 1 # This value must be passed to mainloop()
def thread_function():
asyncio.run(asyncio_loop())
x = threading.Thread(target=thread_function)
x.start()
def mainloop():
while True:
pass # Here I need to get the values from asyncio_loop
mainloop()
我想使用佇列,因為保持資料有序對我來說很重要。
但是對于執行緒我需要使用佇列模塊,但是對于 asyncio 有 asyncio.Queue()。有什么方法可以使用共享佇列,還是我在挖掘錯誤的方向?
我也不考慮套接字,因為我將傳遞類的實體。我想避免不必要的并發癥。
uj5u.com熱心網友回復:
您可以使用普通的執行緒queue.Queue- 它會正常作業,async.Queue 的不同之處在于,用于將資料放入和檢索 int 的方法本身是異步的 - 但由于您將從同步代碼中讀取,因此無法正常作業.
另一方面,在異步代碼中呼叫同步 queue.put 方法沒有任何區別——因為不涉及 I/O,它甚至不會阻塞。
import asyncio
import threading
from queue import Queue
async def asyncio_loop(q):
i = 0
while True:
i = 1 # This value must be passed to mainloop()
q.put(i)
await asyncio.sleep(1)
def thread_function(q):
asyncio.run(asyncio_loop(q))
def mainloop(q):
while True:
print(q.get())
q = Queue()
x = threading.Thread(target=thread_function, args=(q,))
x.start()
mainloop(q)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/520357.html
上一篇:ParallelOptions'MaxDegreeOfParallelism'屬性-為什么我可以指定比我的硬體更多的執行緒?
