await loop.run_in_executor(executor, open_read)
不会返回,直到 await asyncio.shield(get_audio_async(sentance))
将控制权交给事件循环。我拨打了await asyncio.sleep(0)
电话但无济于事。有什么想法吗?
async def read_from_fifo(loop):
executor = ThreadPoolExecutor(max_workers=1)
def open_read():
with open('/tmp/fifo', "rb") as fifo:
bytes = fifo.read()
return bytes.decode('utf-8')
while True:
data = await loop.run_in_executor(executor, open_read)
if not data: continue
message = DecodeMessage(data)
yield message
async def play_audio(sentances):
...
try:
for sentance in sentances:
audio = await asyncio.shield(get_audio_async(sentance))
await asyncio.sleep(0)
audio_server.write(audio)
await asyncio.sleep(0)
audio_server.write(sentance_pause)
audio_server.drain()
except asyncio.CancelledError:
print("cancelling play_audio()")
async def main():
async for message in read_from_fifo(loop):
match message:
case {"method": "narrate_from_cursor", "params":{"buffer": buffer, "cursor_byte_offset":cursor_byte_offset}}:
...
running_task = asyncio.create_task(play_audio(sentances))
case {"method": "cancel"}:
if running_task is not None:
running_task.cancel()
audio_server.flush()
await asyncio.sleep(0)
正在产生控制。
我只需要屈服足够的时间
await asyncio.sleep(0)
await asyncio.sleep(0)
await asyncio.sleep(0)
await asyncio.sleep(0)
到
run_in_executor(executor, open_read)
返回之前。
当阅读消息时,我希望在返回到
play_audio()
之前完全处理该消息。现在使用 run_in_executor()
就足够了,这样阻塞 audio_server.write
调用就不会占用并发性
for i in range(0, stop, step):
await asyncio.sleep(0)
await loop.run_in_executor(None, audio_server.write, audio[i:i+step])