Python 多进程multiprocessing知识梳理( 对比多线程threading )

多进程multiprocessing知识梳理( 对比多线程threading )

语法条目 多线程 多进程
引入模块 from threading import Thread from multiprocessing import Process
新建
启动
等待结束
t=Thread (target=func, args=(100, ) )
t.start( )
t.join()
p = Process(target=func, args=('bob', ))
p.start()
p. join()
数据通信 import queue
q = queue. Queue( )
q. put ( item)
item = q.get()
from multiprocessing import Queue
q = Queue()
q. put([42, None, 'hello'])
item = q.get()
线程安全加锁 from threading import Lock
lock = Lock( )
with lock:
    # do something
from multiprocessing import Lock
lock = Lock( )
with lock:
    # do something
池化技术 from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor() as executor:
    # 方法1
    results = executor. map(func,[1,2,3])

    # 方法2
    future = executor.submit(func,1)
    result = future. result()
from concurrent.futures import ProcessPoolExecutor

with ProcessPoolExecutor() as executor:
    # 方法1
    results = executor.map(func,[1,2,3])

    # 方法2
    future = executor.submit( func,1)
    result = future. result( )
posted @ 2021-06-26 17:50  廿九九  阅读(118)  评论(0)    收藏  举报