zoukankan      html  css  js  c++  java
  • 同步调用与异步调用

    提交任务的两种方式:同步调用与异步调用

    同步调用

    # 同步调用:提交任务后,就在原地等待任务执行完毕,拿到结果,再执行下一行代码.导致程序是串行执行
    import time
    import random
    from concurrent.futures import ThreadPoolExecutor
    
    
    def work(name):
        print("%s is working" % name)
        time.sleep(random.randint(7, 13))
        res = random.randint(7, 13) * "#"
        return {"name": name, "res": res}
    
    
    def weigh(job):
        name = job["name"]
        size = len(job["res"])
        print("%s 工作量 <%s>" % (name, size))
    
    
    if __name__ == "__main__":
        pool = ThreadPoolExecutor(13)    # 人员数目
    
        job1 = pool.submit(work, "alex").result()
        weigh(job1)
        job2 = pool.submit(work, "jack").result()
        weigh(job2)
        job3 = pool.submit(work, "egon").result()
        weigh(job3)
    

      使程序编程串行

    异步调用

    # 异步调用:提交完任务后,不等待任务执行完毕,
    import time
    import random
    from concurrent.futures import ThreadPoolExecutor
    
    
    def work(name):
        print("%s is working" % name)
        time.sleep(random.randint(7, 13))
        res = random.randint(7, 13) * "#"
        return {"name": name, "res": res}
    
    
    def weigh(job):
        job = job.result()
        name = job["name"]
        size = len(job["res"])
        print("%s 工作量 <%s>" % (name, size))
    
    
    if __name__ == "__main__":
        pool = ThreadPoolExecutor(13)    # 人员数目
    
        job1 = pool.submit(work, "alex").add_done_callback(weigh)    # pool.submit(work, "alex")这个对象当作结果传给weigh
        job2 = pool.submit(work, "jack").add_done_callback(weigh)
        job3 = pool.submit(work, "egon").add_done_callback(weigh)
    

    阻塞:是进程运行的一种状态,进程运行是碰到I/O就进行阻塞状态,会被剥夺走cpu的执行权限。

    同步不同于阻塞,同步:是提交任务的一种方式,如果提交的任务是一个纯计算的同步,没有I/O,提交后要等,没有阻塞。

  • 相关阅读:
    C#题型补充
    php数组
    PHP字符串
    动态网页制作PHP常用的正则表达式
    Objective-C:Foundation框架-常用类-NSArray
    Objective-C:Foundation框架-常用类-NSMutableString
    Objective-C:Foundation框架-常用类-NSString全解
    Objective-C:Block
    Objective-C:Category
    Objective-C:@property参数详解
  • 原文地址:https://www.cnblogs.com/fantsaymwq/p/10134640.html
Copyright © 2011-2022 走看看