1. 程式人生 > >同步調用與異步調用

同步調用與異步調用

one back 一行 col 編程 div aps alex sleep

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

同步調用

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

同步調用與異步調用