使用python怎么实现在协程中增加任务

  介绍

这篇文章主要介绍了使用python怎么实现在协程中增加任务,此处通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考价值,需要的朋友可以参考下:

python是什么意思

python是一种跨平台的,具有解释性,编译性,互动性和面向对象的脚本语言,其最初的设计是用于编写自动化脚本,随着版本的不断更新和新功能的添加,常用于用于开发独立的项目和大型项目。

<强> 1,添加一个任务

task2 =, visit_url (& # 39; http://another.com& # 39;,, 3)   asynicio.run (task2)

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

import  asyncio   import 时间   async  def  visit_url (url, response_time):   “““才能访问,url"““   await 才能asyncio.sleep (response_time)   return 才能;f"访问{url},,已得到返回结果,      async  def  run_task ():   “““才能收集子任务“““   时间=task 才能;visit_url (& # 39; http://wangzhen.com& # 39;,, 2)   时间=task_2 才能;visit_url (& # 39; http://another& # 39;,, 3)   await 才能;asyncio.run(任务)   await 才能asyncio.run (task_2)   asyncio.run (run_task ())   打印(f"消耗时间:{time.perf_counter(),安康;start_time}“)

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

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

async  def  run_task ():   “““才能收集子任务“““   时间=task 才能;visit_url (& # 39; http://wangzhen.com& # 39;,, 2)   时间=task_2 才能;visit_url (& # 39; http://another& # 39;,, 3)   await 才能asynicio.gather (task1, task2)

实例扩展:

import  asyncio   得到threading  import 线程   ,   ,   async  def  production_task ():   小姐:才能=0   while 才能正确的:   ,,,#,将消费这个协程每秒注册一个到运行在线程中的循环,thread_loop每秒会获得一个一直打印我的无限循环任务   ,,,asyncio.run_coroutine_threadsafe(消费(i),   ,,,,,,,,,,,,,,,,,,,,thread_loop), #,注意:run_coroutine_threadsafe 这个方法只能用在运行在线程中的循环事件使用   ,,,await  asyncio.sleep(1), #,必须加等待   ,,,小姐:+=1   ,   ,   async  def 消费(我):   while 才能正确的:   ,,,print(“我是第{}任务“.format(我))   ,,,await  asyncio.sleep (1)   ,   ,   def  start_loop(循环):   #,才能运行事件循环,循环,以参数的形式传递进来运行   asyncio.set_event_loop才能(循环)   loop.run_forever才能()   ,   ,   时间=thread_loop  asyncio.new_event_loop(), #,获取一个事件循环   run_loop_thread =,线程(目标=start_loop, arg游戏=(thread_loop)), #,将次事件循环运行在一个线程中,防止阻塞当前主线程   run_loop_thread.start(), #,运行线程,同时协程事件循环也会运行   ,   时间=advocate_loop  asyncio.get_event_loop(), #,将生产任务的协程注册到这个循环中   advocate_loop.run_until_complete (production_task()), #,运行次循环

到此这篇关于使用python怎么实现在协程中增加任务的文章就介绍到这了,更多相关使用python怎么实现在协程中增加任务的内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

使用python怎么实现在协程中增加任务