回顧一下線程和進程python
線程與進程的區別windows
守護線程:多線程
隊列:app
兩種方式:async
生產者消費者模型:spa
生產包子,線程
吃包子3d
事件 event:blog
紅綠燈模型隊列
何時須要多線程:
多進程:
例子:
每個子進程都有一個父進程啓動:
from multiprocessing import Process import os def info(title): print(title) print('module name:', __name__) print('parent process:', os.getppid()) print('process id:', os.getpid()) print("\n\n") def f(name): info('\033[31;1mcalled from child process function f\033[0m') print('hello', name) if __name__ == '__main__': info('\033[32;1mmain process line\033[0m') p = Process(target=f, args=('bob',)) p.start()
進程間通訊:
實踐進程q
from multiprocessing import Process,Queue def f(qq): qq.put(['yang',12,'hehe']) if __name__ == '__main__': q = Queue() p = Process(target=f,args=(q,)) p.start() print(q.get())
實踐:
from multiprocessing import Process, Pipe def f(conn): conn.send([42, None, 'hello from child']) conn.send([42, None, 'hello from child2']) print("from parent:",conn.recv()) conn.close() if __name__ == '__main__': parent_conn, child_conn = Pipe() p = Process(target=f, args=(child_conn,)) p.start() print(parent_conn.recv()) # prints "[42, None, 'hello']" print(parent_conn.recv()) # prints "[42, None, 'hello']" parent_conn.send("張洋可好") # prints "[42, None, 'hello']" p.join()
進程之間數據的真正共享:
實踐,進程間共享數據:
from multiprocessing import Process,Manager import os def f(dic,list): dic[os.getpid()] = os.getpid() list.append(os.getpid()) print(list) if __name__ == '__main__': with Manager() as manager: d = manager.dict() l = manager.list(range(5)) p_list = [] for i in range(10): p = Process(target=f,args=(d,l)) p.start() p_list.append(p) for res in p_list: res.join() print(d) print(l)
multiprocess
Queue \ Pipe 只是實現進程間數據的傳遞
Manager 實現了進程間數據的共享,即多個進程能夠修改同一份數據
這裏有個坑:
windows 多進程 必須加
否則會報錯
進程池:
進城池有兩種方法: