• 技术文章 >Python技术 >Python基础教程

    python在协程中增加任务

    小妮浅浅小妮浅浅2021-02-26 18:14:54原创4723

    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)

    以上就是python在协程中增加任务的方法,希望能对大家有所帮助。更多Python学习指路:python基础教程

    专题推荐:python协程
    品易云
    上一篇:python pyg2plot的原理 下一篇:python如何对多个CSV文件进行读取

    相关文章推荐

    • python常量折叠是什么• python元组拆包如何实现?• python如何定义具名元组?• python线程优先级队列有哪些?• python中pyg2plot如何使用?• python pyg2plot的原理

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网