首页 > 其他分享 >✍74 asyncio随笔

✍74 asyncio随笔

时间:2022-11-10 15:36:45浏览次数:52  
标签:__ task name 74 func time 随笔 asyncio

一.asyncio.wait 和 asyncio.gather 的异同

https://www.jianshu.com/p/6872bf356af7

1. 异同点综述

image-20220407093517671

2. asyncio.wait 用法

  • 最常见的写法是:await asyncio.wait(task_list)
import asyncio
import arrow


def current_time():
    '''
    获取当前时间
    :return:
    '''
    cur_time = arrow.now().to('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss')
    return cur_time


async def func(sleep_time):
    func_name_suffix = sleep_time        # 使用 sleep_time(函数 I/O 等待时长)作为函数名后缀,以区分任务对象
    print(f"[{current_time()}] 执行异步函数 {func.__name__}-{func_name_suffix}")
    await asyncio.sleep(sleep_time)
    print(f"[{current_time()}] 函数 {func.__name__}-{func_name_suffix} 执行完毕")
    return f"【[{current_time()}] 得到函数 {func.__name__}-{func_name_suffix} 执行结果】"


async def run():
    task_list = []
    for i in range(5):
        task = asyncio.create_task(async_func(i))
        task_list.append(task)

    done, pending = await asyncio.wait(task_list, timeout=None)
    for done_task in done:
        print((f"[{current_time()}] 得到执行结果 {done_task.result()}"))

def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())


if __name__ == '__main__':
    main()

3. asyncio.gather 用法

  • 最常见的用法是:await asyncio.gather(*task_list)
import asyncio
import arrow


def current_time():
    '''
    获取当前时间
    :return:
    '''
    cur_time = arrow.now().to('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss')
    return cur_time


async def func(sleep_time):
    func_name_suffix = sleep_time     # 使用 sleep_time(函数 I/O 等待时长)作为函数名后缀,以区分任务对象
    print(f"[{current_time()}] 执行异步函数 {func.__name__}-{func_name_suffix}")
    await asyncio.sleep(sleep_time)
    print(f"[{current_time()}] 函数 {func.__name__}-{func_name_suffix} 执行完毕")
    return f"【[{current_time()}] 得到函数 {func.__name__}-{func_name_suffix} 执行结果】"


async def run():
    task_list = []
    for i in range(5):
        task = asyncio.create_task(func(i))
        task_list.append(task)
    results = await asyncio.gather(*task_list)
    for result in results:
        print((f"[{current_time()}] 得到执行结果 {result}"))


def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())


if __name__ == '__main__':
    main()

2022.04.14 (create_task 使用)

今天晚上和同时讨论研究 事件循环的 create_task 可以在哪里运行

讨论的似懂非懂的,可能我还在做另一件事哈哈, 不过好在实验室成功的

1.结论

loop = asyncio.get_event_loop()
loop.create_task(main())  # 可以在协程内外使用

asyncio.create_task(func())  # 只能在协程内部使用
  • asyncio.create_task 源码 :

image-20220414205453879

在该方法内只有 get_running_loop() 方法,但在此之前没有 get_event_loop() 生成事件循环

所以要么传一个 loop 进去(修改源码试了试可以),要么在协程内部使用

标签:__,task,name,74,func,time,随笔,asyncio
From: https://www.cnblogs.com/songhaixing/p/16877183.html

相关文章

  • leetcode744
    寻找比目标字母大的最小字母Category Difficulty Likes Dislikesalgorithms Easy(45.91%) 249 -TagsCompanies给你一个排序后的字符列表letters,列表中只包含小写英......
  • 白嫖永久服务器1668060067460
    阿贝云服务器注册免费领取1核1g内存5m宽带10g内存的云服务器,对于个人来说完全够用了。还有免费备案和虚拟主机,免备案对于搭建个人博客就很方便,部署了小项目上去,运行流畅不......
  • leetcode374
    猜数字大小Category Difficulty Likes Dislikesalgorithms Easy(51.88%) 265 -Tagsbinary-searchCompanies猜数字游戏的规则如下:每轮游戏,我都会从1到n随机选择......
  • asyncio
    IO密集型应用IO密集型应用CPU等待IO时间远大于CPU自身运行时间,太浪费;常见的IO密集型业务包括:浏览器交互、磁盘请求、网络爬虫、数据库请求等  Python世界......
  • P2474 题解
    前言题目传送门!更好的阅读体验?差分约束。思路预处理维护两个数组\(mn_{i,j}\)与\(mx_{i,j}\),表示砝码\(i\)与砝码\(j\)重量差值的最小最大。我们分类讨论:......
  • POJ 2774 Long Long Message
    DescriptionThelittlecatismajoringinphysicsinthecapitalofByterland.Apieceofsadnewscomestohimthesedays:hismotherisgettin......
  • HUST 1374 Just Another Game
    DescriptionHHandLLalwaysplaygamestogether,however,LLwoneverytime~~.ThatmakeHHveryunhappy,sothistimeHHisdesigninganewgameforbeat......
  • HDU 5874 Friends and Enemies
    ProblemDescriptionOnanisolatedisland,livedsomedwarves.Aking(notadwarf)ruledtheislandandtheseasnearby,thereareabundantcobblestones......
  • POJ 1743 Musical Theme
    DescriptionAmusicalmelodyisrepresentedasasequenceofN(1<=N<=20000)notesthatareintegersintherange1..88,eachrepresentingakeyonthepi......
  • CF1747 题解
    比赛链接:https://codeforces.com/contest/1747题解:AB水题//bySkyRainWind#include<cstdio>#include<vector>#include<cstring>#include<iostream>#include......