如何使用asyncio同时运行2个循环
问题描述:
对于asyncio来说,我很新,所以很多东西离我的理解还有很远的距离,无论如何。如何使用asyncio同时运行2个循环
我有一个主要的while循环,基本上只是使用PyGame在屏幕上绘制一些东西,而我想要做的是,异步运行另一个while循环,不断更新一些要呈现的数据。
async def update(reader, writer):
while True:
json_data = await reader.read(1000)
self.json_data = json.loads(json_data)
def run(self):
while True:
self.draw()
答
尝试线程:
import threading
async def update(reader, writer):
while True:
json_data = await,reader.read(1000)
self.json_data = json.loads(json_data)
def run(self):
while True:
self.draw()
t = threading.Thread(target=update,args=(reader,writer))
t2 = threading.Thread(target=run,args=(self))
t.start()
t2.start()
线程将同时运行这两个进程!
+0
感谢您的回复,但我认为asyncio会以任何方式完成这项工作......我不想从一开始就使用线程。 – Paradisee
只需创建[两个不同的任务](https://asyncio.readthedocs.io/en/latest/hello_world.html#creating-tasks)。 'self.draw()'应该是异步的。必要时使用['loop.run_in_executor'](https://asyncio.readthedocs.io/en/latest/threads.html)。 – Vincent