gevent.sleep(0) 的 asyncio 等价物是什么
What's the equivalent in asyncio of gevent.sleep(0)
如果我以后想要一些代码到 运行,我可以调用 gevent.sleep(0) 从当前的 greenlet 中产生,如何在异步中处理它?
例如
def spawn(f):
def wrapper(*args, **kwargs):
return gevent.spawn(f, *args, **kwargs)
return wrapper
@spawn
def f(a, b):
gevent.sleep(0) # gevent.idle()
print(a + b)
@spawn
def g():
print("hello")
f(1, 3)
f(4, 5)
g()
gevent.sleep(3)
"""
Expected:
hello
4
9
"""
在这种情况下,g 将 运行 领先于 f。在 asyncio 中有类似的东西吗?
gevent.sleep(time)
等价于 asyncio
中的 await asyncio.sleep(time)
。如果您调用 await asyncio.sleep(time)
,调用者将 sleep/block 任务 任务 ,如果有其他可用任务,他们将 运行。在声明的 time
通过后,调用者任务将可用于执行。
示例:
import asyncio
async def f():
await asyncio.sleep(2)
print('This is function f!')
async def g():
print("This is function g!")
async def main():
loop = asyncio.get_event_loop()
loop.create_task(f())
loop.create_task(g())
await asyncio.sleep(10)
asyncio.run(main())
如果我以后想要一些代码到 运行,我可以调用 gevent.sleep(0) 从当前的 greenlet 中产生,如何在异步中处理它? 例如
def spawn(f):
def wrapper(*args, **kwargs):
return gevent.spawn(f, *args, **kwargs)
return wrapper
@spawn
def f(a, b):
gevent.sleep(0) # gevent.idle()
print(a + b)
@spawn
def g():
print("hello")
f(1, 3)
f(4, 5)
g()
gevent.sleep(3)
"""
Expected:
hello
4
9
"""
在这种情况下,g 将 运行 领先于 f。在 asyncio 中有类似的东西吗?
gevent.sleep(time)
等价于 asyncio
中的 await asyncio.sleep(time)
。如果您调用 await asyncio.sleep(time)
,调用者将 sleep/block 任务 任务 ,如果有其他可用任务,他们将 运行。在声明的 time
通过后,调用者任务将可用于执行。
示例:
import asyncio
async def f():
await asyncio.sleep(2)
print('This is function f!')
async def g():
print("This is function g!")
async def main():
loop = asyncio.get_event_loop()
loop.create_task(f())
loop.create_task(g())
await asyncio.sleep(10)
asyncio.run(main())