📌  相关文章
📜  如何永远运行两个异步函数Python

📅  最后修改于: 2022-05-13 01:55:42.026000             🧑  作者: Mango

如何永远运行两个异步函数Python

异步编程是一种编程类型,我们可以在不阻塞主任务(函数)的情况下执行多个任务。在Python,有多种方法可以同时执行多个函数,其中一种方法是使用asyncio 。异步编程允许您编写在单个线程中运行的并发代码。

注意: Asyncio 不使用线程或多处理来使程序异步。

协程协程是一种通用的控制结构,流量控制在两个不同的例程之间协同传递而不返回。在 asyncio 中,可以通过在 def 之前使用 async 关键字来创建协程。

async def speak_async():
   for i in range(100):
       print("Hello I'm Abhishek, writer on GFG")

如果您尝试直接运行异步函数,您将收到运行时警告:

要运行异步函数(协程),您必须使用事件循环调用它。

事件循环:您可以将事件循环视为运行异步任务和回调、执行网络 IO 操作和运行子进程的函数。

示例 1:运行 async函数以运行单个异步函数的事件循环示例:

Python3
import asyncio
  
  
async def function_asyc():
    for i in range(5):
        print("Hello, I'm Abhishek")
        print("GFG is Great")
    return 0
  
# to run the above function we'll 
# use Event Loops these are low 
# level functions to run async functions
loop = asyncio.get_event_loop()
loop.run_until_complete(function_asyc())
loop.close()
print("HELLO WORLD")
print("HELLO WORLD")
  
# You can also use High Level functions Like:
# asyncio.run(function_asyc())


Python3
import asyncio
  
  
async def function_asyc():
    for i in range(100000):
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG is Great")
    return 0
  
async def function_2():
    print("\n HELLO WORLD \n")
    return 0
  
async def main():
    f1 = loop.create_task(function_asyc())
    f2 = loop.create_task(function_2())
    await asyncio.wait([f1, f2])
  
# to run the above function we'll 
# use Event Loops these are low 
# level functions to run async functions
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
  
# You can also use High Level functions Like:
# asyncio.run(function_asyc())


Python3
import asyncio
  
  
async def function_asyc():
    
    for i in range(100000):
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG is Great")
              
            # New Line Added
            await asyncio.sleep(0.01)
    return 0
  
async def function_2():
    print("\n HELLO WORLD \n")
    return 0
  
async def main():
    f1 = loop.create_task(function_asyc())
    f2 = loop.create_task(function_2())
    await asyncio.wait([f1, f2])
  
# to run the above function we'll 
# use Event Loops these are low level
# functions to run async functions
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
  
# You can also use High Level functions Like:
# asyncio.run(function_asyc())


Python3
import asyncio
  
  
async def function_asyc():
    i = 0
    while i < 1000000:
        i += 1
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG is Great")
            await asyncio.sleep(0.01)
  
async def function_2():
    print("\n HELLO WORLD \n")
  
  
async def main():
    
    # New Line Added
    while True:
        f1 = loop.create_task(function_asyc())
        f2 = loop.create_task(function_2())
        await asyncio.wait([f1, f2])
  
# to run the above function we'll 
# use Event Loops these are low
# level functions to run async functions
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()


Python3
import asyncio
  
  
async def function_asyc():
    i = 0
      
    while True:
        i += 1
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG is Great")
            await asyncio.sleep(0.01)
  
async def function_2():
    while True:
        await asyncio.sleep(0.01)
        print("\n HELLO WORLD \n")
  
loop = asyncio.get_event_loop()
asyncio.ensure_future(function_asyc())
asyncio.ensure_future(function_2())
loop.run_forever()


输出
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
HELLO WORLD
HELLO WORLD

示例 2:一次执行多个函数。要做到这一点,我们必须创建一个新的异步函数(主),并呼吁所有异步功能(这是我们要在同一时间运行)的新函数(主)。然后使用事件循环调用新的(主)函数……

代码:

蟒蛇3

import asyncio
  
  
async def function_asyc():
    for i in range(100000):
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG is Great")
    return 0
  
async def function_2():
    print("\n HELLO WORLD \n")
    return 0
  
async def main():
    f1 = loop.create_task(function_asyc())
    f2 = loop.create_task(function_2())
    await asyncio.wait([f1, f2])
  
# to run the above function we'll 
# use Event Loops these are low 
# level functions to run async functions
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
  
# You can also use High Level functions Like:
# asyncio.run(function_asyc())
输出

Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great

 HELLO WORLD 

注意: .create_task() 用于一次运行多个异步函数。

例3:这里可以看到function_async()和function_2()不是并发运行的,先显示function_async()的输出,然后显示function_2()的输出,表示function_2()执行后正在执行function_async() 的。

但我们不想那样!我们希望两个函数同时取得进展,因此为了在Python实现这一点,我们必须明确告诉计算机何时从一个函数转移到另一个函数。

代码:

蟒蛇3

import asyncio
  
  
async def function_asyc():
    
    for i in range(100000):
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG is Great")
              
            # New Line Added
            await asyncio.sleep(0.01)
    return 0
  
async def function_2():
    print("\n HELLO WORLD \n")
    return 0
  
async def main():
    f1 = loop.create_task(function_asyc())
    f2 = loop.create_task(function_2())
    await asyncio.wait([f1, f2])
  
# to run the above function we'll 
# use Event Loops these are low level
# functions to run async functions
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
  
# You can also use High Level functions Like:
# asyncio.run(function_asyc())
输出
Hello, I'm Abhishek
GFG is Great

 HELLO WORLD 

Hello, I'm Abhishek
GFG is Great

现在你可以看到,第二个函数是在运行函数(function_async())的执行过程中执行的。所以这些是基础,现在让我们看看如何永远运行两个异步函数。

永远运行两个异步函数Python:

方法 1:只需在主函数使用 while True 循环:

蟒蛇3

import asyncio
  
  
async def function_asyc():
    i = 0
    while i < 1000000:
        i += 1
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG is Great")
            await asyncio.sleep(0.01)
  
async def function_2():
    print("\n HELLO WORLD \n")
  
  
async def main():
    
    # New Line Added
    while True:
        f1 = loop.create_task(function_asyc())
        f2 = loop.create_task(function_2())
        await asyncio.wait([f1, f2])
  
# to run the above function we'll 
# use Event Loops these are low
# level functions to run async functions
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

输出:

Hello, I'm Abhishek
GFG is Great

 HELLO WORLD 

Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
.
.
.
.

方法 2:对这两个函数使用 while True 循环并使用 asyncio.ensure_future() 和 loop.run_forever() 调用它们

注意: ensure_future 允许我们在后台执行协程,而无需显式等待它完成。

蟒蛇3

import asyncio
  
  
async def function_asyc():
    i = 0
      
    while True:
        i += 1
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG is Great")
            await asyncio.sleep(0.01)
  
async def function_2():
    while True:
        await asyncio.sleep(0.01)
        print("\n HELLO WORLD \n")
  
loop = asyncio.get_event_loop()
asyncio.ensure_future(function_asyc())
asyncio.ensure_future(function_2())
loop.run_forever()

输出:

Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great

 HELLO WORLD 

Hello, I'm Abhishek
GFG is Great
.
.
.