住手异步运行()忽略了我剩下的Cod

2024-10-02 02:32:19 发布

您现在位置:Python中文网/ 问答频道 /正文

只要同步代码继续运行,我就打算运行一个异步函数(它执行与程序其他部分相关的操作,但不返回任何内容)。但是,在我运行asyncio.run()命令之后,程序就永远只执行异步命令。你知道吗

我尝试过一些基本的线程和多进程池方法,但我发现这是我尝试过的最成功的方法:

# There's some code up here (A), and it runs synchronously and fine.

# Here's the asynchronous code (B).
pauseAsynchronousFunction = False

async def asynchronousFunction():
    global pauseAsynchronousFunction
    # Do stuff before hitting the while loop.
    while True:
        if pauseAsynchronousFunction == False:
            # Do some stuff.
        else:
            # Do some other stuff.

asyncio.run(pauseAsynchronousFunction())

# More synchronous code is down here (C), which it never reaches.

我可以看出它没有像我期望的那样工作,因为下面的另一个函数(在C中)调用相同的全局变量pauseAsynchronousFunction,并将其从False切换到True,然后在运行完成后再次返回False。这种切换从未发生过。你知道吗

我猜问题要么与while True有关,我不明白为什么它是异步的,要么与不包含await语句有关。我还缺什么?你知道吗

更新:

我在pypy的帮助下进行了一些调试尝试,得到了这个结果。你知道吗


pauseAsynchronousFunction = False

async def fun2():
    global pauseAsynchronousFunction
    while True:
        if pauseAsynchronousFunction == False:
            #do stuff
        else:
            #do other stuff

async def fun1():
    global pauseAsynchronousFunction
    pauseAsynchronousFunction = True
    #do stuff here that you wanted to do after the `asyncio.run` above
    pauseAsynchronousFunction = False
    return stuff

async def main():
    await asyncio.gather(
        fun1(),
        fun2(),
    )

asyncio.run(main)

问题似乎是: pauseAsynchronousFunction切换到True,但不会切换回fun(1)末尾的False。你知道吗


Tags: therunasynciofalsetrueasyncheredef
1条回答
网友
1楼 · 发布于 2024-10-02 02:32:19

asyncio.run将阻塞,直到异步函数全部返回。因此,在asyncio.run()之后的代码应该转换为异步函数,即

import asyncio

async def fun2():
    global pauseAsynchronousFunction
    while True:
        if pauseAsynchronousFunction == False:
            print('not paused')
        else:
            print('paused')
        await asyncio.sleep(1)

async def fun1():
    global pauseAsynchronousFunction
    pauseAsynchronousFunction = True
    print('im pausing')
    await asyncio.sleep(5)
    print('im unpausing')
    pauseAsynchronousFunction = False
    return 0

async def main():
    await asyncio.gather(
        fun1(),
        fun2(),
    )

await main()

下面是一个使用线程和事件的替代答案:

import threading
import time

should_pause = threading.Event()

def fun2():
    while True:
        if should_pause.is_set():
            print('paused')
        else:
            print('not paused')
        time.sleep(1)


t = threading.Thread(target=fun2)
t.start()
should_pause.set()
print('waiting')
time.sleep(5)
print('finished-waiting')
should_pause.clear()

相关问题 更多 >

    热门问题