时间:2021-05-23
1、添加一个任务
task2 = visit_url('http://another.com', 3)asynicio.run(task2)2、这 2 个程序一共消耗 5s 左右的时间。并没有发挥并发编程的优势
import asyncioimport timeasync 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 asynciofrom 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在协程中增加任务实例操作的文章就介绍到这了,更多相关python在协程中增加任务内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了Python协程yield与协程greenlet简单用法。分享给大家供大家参考,具体如下:协程协程,又称微线程,纤程。英文名Coroutine。协
协程,又称微线程,纤程。英文名Coroutine。协程是Python中另外一种实现多任务的方式,只不过比线程更小,占用更小执行单元(理解为需要的资源)。为啥说它
单线程+多任务异步协程协程在函数(特殊函数)定义的时候,使用async修饰,函数调用后,内部语句不会立即执行,而是会返回一个协程对象任务对象任务对象=高级的协程
本文实例讲述了python协程用法。分享给大家供大家参考。具体如下:把函数编写为一个任务,从而能处理发送给他的一系列输入,这种函数称为协程defprint_ma
这篇文章主要介绍了python已协程方式处理任务实现过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下#从g