脚本专栏 
首页 > 脚本专栏 > 浏览文章

python在协程中增加任务实例操作

(编辑:jimmy 日期: 2025/2/25 浏览:3 次 )

1、添加一个任务

task2 = visit_url('http://another.com', 3)
asynicio.run(task2)

2、这 2 个程序一共消耗 5s 左右的时间。并没有发挥并发编程的优势

import asyncio
import time
async def visit_url(url, response_time):
  """访问 url"""
  await asyncio.sleep(response_time)
  return f"访问{url}, 已得到返回结果"

async def run_task():
  """收集子任务"""
  task = visit_url('http://wangzhen.com', 2)
  task_2 = visit_url('http://another', 3)
  await asyncio.run(task)
  await asyncio.run(task_2)
asyncio.run(run_task())
print(f"消耗时间:{time.perf_counter() - start_time}")

3、如果是并发编程,这个程序只需要消耗 3s,也就是task2的等待时间。

要想使用并发编程形式,需要把上面的代码改一下。asyncio.gather 会创建 2 个子任务,当出现 await 的时候,程序会在这 2 个子任务之间进行调度。

async def run_task():
  """收集子任务"""
  task = visit_url('http://wangzhen.com', 2)
  task_2 = visit_url('http://another', 3)
  await asynicio.gather(task1, task2)

实例扩展:

import asyncio
from threading import Thread
 
 
async def production_task():
  i = 0
  while True:
    # 将consumption这个协程每秒注册一个到运行在线程中的循环,thread_loop每秒会获得一个一直打印i的无限循环任务
    asyncio.run_coroutine_threadsafe(consumption(i),
                     thread_loop) # 注意:run_coroutine_threadsafe 这个方法只能用在运行在线程中的循环事件使用
    await asyncio.sleep(1) # 必须加await
    i += 1
 
 
async def consumption(i):
  while True:
    print("我是第{}任务".format(i))
    await asyncio.sleep(1)
 
 
def start_loop(loop):
  # 运行事件循环, loop以参数的形式传递进来运行
  asyncio.set_event_loop(loop)
  loop.run_forever()
 
 
thread_loop = asyncio.new_event_loop() # 获取一个事件循环
run_loop_thread = Thread(target=start_loop, args=(thread_loop,)) # 将次事件循环运行在一个线程中,防止阻塞当前主线程
run_loop_thread.start() # 运行线程,同时协程事件循环也会运行
 
advocate_loop = asyncio.get_event_loop() # 将生产任务的协程注册到这个循环中
advocate_loop.run_until_complete(production_task()) # 运行次循环
上一篇:python pyg2plot的原理知识点总结
下一篇:python 制作本地应用搜索工具
一句话新闻
一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?