同步调用与异步调用

2022-09-08 10:21:00 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

同步调用和异步调用是两种提交任务的方式

同步调用:提交完任务后,就在原地等待任务执行完毕,拿到运行结果/返回值后再执行下一步,同步调用下任务是串行执行。

异步调用:提交完任务后,不会再原地等待任务执行完毕,直接执行下一行代码,异步调用时并发执行。

异步调用,几乎同时下达任务

代码语言:javascript复制
from concurrent.futures import ProcessPoolExecutor
import os, time,random



def task(x):
    print("%s is running" % os.getpid())
    time.sleep(random.randint(1,3))
    return x**2

if __name__=="__main__":
    p = ProcessPoolExecutor()
    futures = []
    for i in range(10):
        future = p.submit(task,i)#返回计算结果
        futures.append(future)
    p.shutdown(wait=True)#默认waiti为True 等待十个进程任务执行完,关闭进程池的入口。
    for future in futures:
        print(future.result())
    print("主")
代码语言:javascript复制
结果为:

10760 is running
10564 is running
12848 is running
3928 is running
10564 is running
12848 is running
10760 is running
3928 is running
10760 is running
10564 is running
0
1
4
9
16
25
36
49
64
81
主

如果把p.shutdown(wait=True)去掉,则会出现结果穿插在进程中

代码语言:javascript复制
2908 is running
8092 is running
10376 is running
13136 is running
8092 is running
2908 is running
0
1
8092 is running
10376 is running
4
2908 is running
10376 is running
9
16
25
36
49
64
81
主

同步调用:

代码语言:javascript复制
def task(x):
    print("%s is running" % os.getpid())
    time.sleep(random.randint(1,3))
    return x**2

if __name__=="__main__":
    p = ProcessPoolExecutor()
    for i in range(10):
        res = p.submit(task,i).result()#返回计算结果
        print(res)
    print("主")
代码语言:javascript复制
结果为:

8360 is running
0
472 is running
1
4888 is running
4
12980 is running
9
8360 is running
16
472 is running
25
4888 is running
36
12980 is running
49
8360 is running
64
472 is running
81
主

串行执行,效率低下。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/157315.html原文链接:https://javaforall.cn

0 人点赞