1 回答

TA貢獻1802條經驗 獲得超5個贊
這種方法總體上很好。你有一些問題:
(1)幾乎所有的asyncio對象都不是線程安全的
(2) 您的代碼本身不是線程安全的。如果任務出現在之后needed_tasks = _tasks.copy()
但之前怎么辦_tasks = []
?這里需要一把鎖。順便說一句,復制是沒有意義的。簡單needed_tasks = _tasks
就行了。
(3) 一些 asyncio 結構是線程安全的。使用它們:
import threading
import asyncio
# asyncio.get_event_loop() creates a new loop per thread. Keep
# a single reference to the main loop. You can even try
#? ?_loop = asyncio.new_event_loop()
_loop = asyncio.get_event_loop()
def get_app_loop():
? ? return _loop
def asyncio_thread():
? ? loop = get_app_loop()
? ? asyncio.set_event_loop(loop)
? ? loop.run_forever()
def add_asyncio_task(task):
? ? asyncio.run_coroutine_threadsafe(task, get_app_loop())
def start_asyncio_loop():
? ? t = threading.Thread(target=asyncio_thread)
? ? t.start()
添加回答
舉報