位置: IT常识 - 正文
推荐整理分享python在协程中增加任务(python的协程),希望有所帮助,仅作参考,欢迎阅读内容。
文章相关热门搜索词:python协程在运行过程中有哪些状态,python协程用法,python 协程 yield,python 协程能加速for循环吗,python 协程 yield,python协程用法,python协程用法,python 协程 yield,内容如对您有帮助,希望把文章链接给更多的朋友!
1、添加一个任务
task2=visit_url('http://another.com',3)asynicio.run(task2)2、这 2 个程序一共消耗 5s 左右的时间。并没有发挥并发编程的优势
importasyncioimporttimeasyncdefvisit_url(url,response_time):"""访问url"""awaitasyncio.sleep(response_time)returnf"访问{url},已得到返回结果"asyncdefrun_task():"""收集子任务"""task=visit_url('http://wangzhen.com',2)task_2=visit_url('http://another',3)awaitasyncio.run(task)awaitasyncio.run(task_2)asyncio.run(run_task())print(f"消耗时间:{time.perf_counter()-start_time}")3、如果是并发编程,这个程序只需要消耗 3s,也就是task2的等待时间。要想使用并发编程形式,需要把上面的代码改一下。asyncio.gather 会创建 2 个子任务,当出现 await 的时候,程序会在这 2 个子任务之间进行调度。
asyncdefrun_task():"""收集子任务"""task=visit_url('http://wangzhen.com',2)task_2=visit_url('http://another',3)awaitasynicio.gather(task1,task2)上一篇:python中filter()的多种筛选(python filter dict)
下一篇:驱动开发:内核字符串转换方法(驱动开发:内核是什么)
友情链接: 武汉网站建设