码迷,mamicode.com
首页 > 其他好文 > 详细

同步调用与异步调用

时间:2018-12-18 02:02:54      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:任务   执行   调用   thread   工作量   exec   结果   lex   方式   

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

同步调用

# 同步调用:提交任务后,就在原地等待任务执行完毕,拿到结果,再执行下一行代码.导致程序是串行执行
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,提交后要等,没有阻塞。

同步调用与异步调用

标签:任务   执行   调用   thread   工作量   exec   结果   lex   方式   

原文地址:https://www.cnblogs.com/fantsaymwq/p/10134640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!