Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
async python-从AssertionError生成正确的参数_Python_Asynchronous_Python Asyncio - Fatal编程技术网

async python-从AssertionError生成正确的参数

async python-从AssertionError生成正确的参数,python,asynchronous,python-asyncio,Python,Asynchronous,Python Asyncio,我的要求是同时运行两个函数,如果另一个函数计算速度更快并返回结果,则停止其中一个函数的执行 我知道异步编程或事件循环的知识。我读了这本书,这本书让我 我的示例代码: import time import asyncio as aio async def f(x): time.sleep(1) # to fake fast work print("f say: " + str(x*2)) return x*2 async def s(x): time.sleep

我的要求是同时运行两个函数,如果另一个函数计算速度更快并返回结果,则停止其中一个函数的执行

我知道异步编程或事件循环的知识。我读了这本书,这本书让我

我的示例代码:

import time
import asyncio as aio

async def f(x):
    time.sleep(1) # to fake fast work
    print("f say: " + str(x*2))
    return x*2

async def s(x):
    time.sleep(3) # to fake slow work
    print("s say: " + str(x*2))
    return x**2

x = 10

assert aio.iscoroutinefunction(f)
assert aio.iscoroutinefunction(s)

futures = {f(x), s(x)}

def executor():
    yield from aio.wait(futures, return_when=aio.FIRST_COMPLETED)

done, pending = executor()

但是由于一些未知的原因,它不起作用。

您得到的特定断言与
的错误使用有关。然而,问题更为严重:

我的要求是同时运行两个函数

这不是asyncio的工作方式,没有任何东西是“同时”运行的。相反,可以运行异步函数,直到它们达到通常的阻塞调用为止。异步函数不再阻塞,而是挂起其执行,允许其他协同路由运行。它们必须由一个事件循环驱动,该循环驱动它们,并在某个IO事件允许它们恢复时将它们唤醒

更正确的代码异步IO版本如下所示:

import asyncio

async def f(x):
    await asyncio.sleep(1) # to fake fast work
    print("f say: " + str(x*2))
    return x*2

async def s(x):
    await asyncio.sleep(3) # to fake slow work
    print("s say: " + str(x*2))
    return x**2

async def execute():
    futures = {f(10), s(10)}
    done, pending = await asyncio.wait(futures, return_when=asyncio.FIRST_COMPLETED)
    for fut in pending:
        fut.cancel()
    return done

loop = asyncio.get_event_loop()
done = loop.run_until_complete(execute())
print(done)
特别注意:

  • 使用
    asyncio.sleep()
    代替
    time.sleep()
    。这适用于每个阻塞调用

  • 必须使用
    await
    关键字等待协同程序,例如
    asyncio.sleep
    asyncio.wait
    。这允许协同路由在遇到阻塞调用时暂停自身

  • 异步代码通过事件循环执行,其入口点通常为或


感谢您的详细解释。你的第二段让我觉得我应该使用threadpoolexecutor之类的东西。我在正确的轨道上吗?@vvsLaxman如果函数是同步的,那么你可以使用
循环。在执行器中运行(无,同步函数)
。还要注意,Python的GIL将不允许函数真正同时运行。