同步調用與異步調用

提交任務的兩種方式:同步調用與異步調用python

同步調用

# 同步調用:提交任務後,就在原地等待任務執行完畢,拿到結果,再執行下一行代碼.致使程序是串行執行
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)

  使程序編程串行編程

異步調用dom

# 異步調用:提交完任務後,不等待任務執行完畢,
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,提交後要等,沒有阻塞。spa

相關文章
相關標籤/搜索