簡體   English   中英

在 asyncio 中等待 while 循環

[英]await while loop in asyncio

如何等待while循環? 我有以下代碼片段:

import asyncio
from asyncio.tasks import sleep
import time

running = True

async def f1():
    global running
    print(f"Running: {running}")
    print("f1() started.")

    ### await the while loop below
    while running:
        print(f"Inside while loop")
    ###

    print(f"Running: {running}")
    print("f1() ended")

async def f2():
    global running
    print("f2() started.")
    
    # this should be blocking code
    time.sleep(0.5)
    
    print("f2 ended.")
    running = False

async def main():
    await asyncio.gather(f1(), f2())

asyncio.run(main())

基本上,我想要的是:

# 1. Start f1(). f1() has a while loop.
# 2. Start f2().
# 3. Notify f1() to break the while loop.

我想你必須在 while 循環中加入一些 await asyncio.sleep(0) 左右。 只是需要一些等待電話,讓其他人有機會做某事

import asyncio
from asyncio.tasks import sleep
import time

running = True


async def f1():
    global running
    print(f"Running: {running}")
    print("f1() started.")

    ### await the while loop below
    while running:
        print(f"Inside while loop")
        await asyncio.sleep(0)
    ###

    print(f"Running: {running}")
    print("f1() ended")


async def f2():
    global running
    print("f2() started.")

    # this should be blocking code
    time.sleep(0.5)

    print("f2 ended.")
    running = False


async def main():
    await asyncio.gather(f1(), f2())


asyncio.run(main())

這對我行得通

沒有全局變量:

import asyncio
from asyncio.tasks import sleep
import time


async def f1( q ):
    print("f1() started.")

    ### await the while loop below
    ## Start listener
    event = asyncio.ensure_future( q.get() )
    while True:
        print( "Inside While Loop" )
        if event.done():
            break
        else: 
            await asyncio.sleep( 0.01 )

    ###

    print("f1() ended")

async def f2( q ):
    print("f2() started.")
    
    # this should be blocking code
    time.sleep( 3 )
    
    print("f2 ended.")
    await q.put( 1 )

async def main():
    q = asyncio.Queue( 1 )
    await asyncio.gather(f1( q ), f2( q ))

asyncio.run(main())

但是,由於 f2 被阻塞,它實際上不會在被阻塞時打印“內部事件循環”

所以你會得到 output 像

f1() started.
Inside While Loop
f2() started.
f2 ended.
Inside While Loop
f1() ended

您也可以在該隊列中放置任何東西,不必是1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM