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,提交后要等,没有阻塞。

  • 相关阅读:
    JPA的一对多,多对多用法
    pg数据库中时间查询的方式
    DNS消息格式
    Netty之Java堆外内存扫盲贴
    Netty writeAndFlush() 流程与异步
    Netty之有效规避内存泄漏
    TCP状态变迁图
    TCP/IP详解--发送ACK和RST的场景
    TCP/IP详解--连接状态变迁图CLOSE_WAIT
    TCP中异常关闭链接的意义 异常关闭的情况
  • 原文地址:https://www.cnblogs.com/fantsaymwq/p/10134640.html
Copyright © 2011-2022 走看看