多進程進程間通訊multiprocessing
阿新 • • 發佈:2018-07-27
bin min 得到 rgs desktop isp none tex 線程隊列
#!/usr/bin/env python # Author:Zhangmingda import queue,threading from multiprocessing import Process,Queue def f(q): q.put([234,None,‘Hello‘]) if __name__ == ‘__main__‘: q = queue.Queue() #使用線程隊列運行報錯TypeError: can‘t pickle _thread.lock objects p = Process(target=f,args=(q,)) #啟動一個子進程 #線程報錯p = threading.Thread(target=f,) #啟動線程直接共享主進程內存 p.start() print(q.get()) p.join()
C:\Users\Administrator\Desktop\Python3_study\venv\Scripts\python.exe C:/Users/Administrator/Desktop/Python3_study/day10/進程間通信?.py Traceback (most recent call last): File "C:/Users/Administrator/Desktop/Python3_study/day10/進程間通信?.py運行報錯效果", line 13, in <module> p.start() File "C:\Program Files\Python36\lib\multiprocessing\process.py", line 105, in start self._popen = self._Popen(self) File "C:\Program Files\Python36\lib\multiprocessing\context.py", line 223, in _Popen return _default_context.get_context().Process._Popen(process_obj) File"C:\Program Files\Python36\lib\multiprocessing\context.py", line 322, in _Popen return Popen(process_obj) File "C:\Program Files\Python36\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__ reduction.dump(process_obj, to_child) File "C:\Program Files\Python36\lib\multiprocessing\reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) TypeError: can‘t pickle _thread.lock objects
#!/usr/bin/env python # Author:Zhangmingda import queue,threading from multiprocessing import Process,Queue def f(q): q.put([234,None,‘Hello‘]) if __name__ == ‘__main__‘: # q = queue.Queue() #使用線程隊列運行報錯TypeError: can‘t pickle _thread.lock objects q = Queue() #進程隊列 p = Process(target=f,args=(q,)) #啟動一個子進程 # p = threading.Thread(target=f,) #啟動線程直接共享主進程內存 p.start() print(q.get()) p.join()進程間通訊
進程間通訊原理:本例中等於將父進程中的q克隆了一份給子進程,子進程進行了序列化,在子進程中執行後又反序列化給父進程。所以在父進程中能夠得到子進程對父進程中數據的修改結果。
C:\Users\Administrator\Desktop\Python3_study\venv\Scripts\python.exe C:/Users/Administrator/Desktop/Python3_study/day10/進程間通信?.py [234, None, ‘Hello‘] Process finished with exit code 0運行效果
多進程進程間通訊multiprocessing