ฉันยังใหม่กับ asyncio ใน python เล็กน้อย ฉันพยายามเรียกใช้โค้ดง่ายๆ นี้ แต่ฉันไม่รู้ว่าทำไมฉันถึงได้รับผลลัพธ์ที่ไม่คาดคิด
สิ่งที่ฉันทำคือในฟังก์ชัน outer
ฉันสร้างงานอะซิงก์และจัดเก็บไว้ในอาร์เรย์ tasks
ก่อนที่จะรองานเหล่านี้ ฉันเขียนคำสั่งพิมพ์ print("outer")
ที่ควรจะรันในทุก ๆ การวนซ้ำ และภายในงาน ฉันเขียนคำสั่งพิมพ์อีกอัน print("inner")
ในฟังก์ชัน inner
แต่บางอย่างฉันได้รับผลลัพธ์ที่ไม่คาดคิดได้อย่างไร
นี่คือรหัส -
import asyncio
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(outer(loop))
loop.close()
async def outer(loop):
tasks = []
for i in range(0, 5):
tasks.append(loop.create_task(inner()))
for task in tasks:
print("outer")
await task
async def inner():
print("inner")
await asyncio.sleep(0.5)
if __name__ == '__main__':
main()
นี่คือผลลัพธ์ -
outer
inner
inner
inner
inner
inner
outer
outer
outer
outer
ผลลัพธ์ที่คาดหวังของฉันคือ -
outer
inner
outer
inner
outer
inner
outer
inner
outer
inner
เหตุใด inner
ทั้งหมดจึงพิมพ์ก่อน outer
ขั้นตอนการดำเนินการที่ถูกต้องของ asyncio คืออะไร ขอบคุณล่วงหน้า.
await
จากนั้นจะถูกระงับ... ตัวอย่างของคุณคล้ายกับ ตัวอย่าง coroutine ในเอกสารซึ่งมีผลลัพธ์ที่คล้ายกัน - person wwii   schedule 29.03.2020While a Task is running in the event loop, no other Tasks can run in the same thread. When a Task executes an await expression, the running Task gets suspended, and the event loop executes the next Task.
- person wwii   schedule 29.03.2020for
ครั้งถัดไป หากเป็นเช่นนั้นouter
ก็ควรจะพิมพ์ออกมา - person shikhar srivastava   schedule 30.03.2020