python multiprocessing
阿新 • • 發佈:2020-09-15
from multiprocessing import Process import os # 子程序要執行的程式碼 def run_proc(name): print('Run child process %s (%s)...' % (name, os.getpid())) if __name__=='__main__': print('Parent process %s.' % os.getpid()) p = Process(target=run_proc, args=('test',)) print('Child process will start.') p.start() p.join() print('Child process end.')
# 程序池 import multiprocessing import os import time def run_proc(name): time.sleep(10) print('Run child process %s (%s)...' % (name, os.getpid())) if __name__=='__main__': print('Parent process %s.' % os.getpid()) pool = multiprocessing.Pool(3) plist=[] for i in range(10): pool.apply_async(run_proc, args=('test' + str(i),)) pool.close() pool.join()
# #程序池中的程序如何通訊
程序之前不能共享全域性變數,需要有個公共的佇列來操作存放資訊
# -*- coding: UTF-8 -*- import os import multiprocessing import time def write(q): print("write啟動(%s),父程序為(%s)" % (os.getpid(), os.getppid()))for i in "python": q.put(i) def read(q): print("read啟動(%s),父程序為(%s)" % (os.getpid(), os.getppid())) for i in range(q.qsize()): print("read從Queue獲取到訊息:%s" % q.get(True)) if __name__ == "__main__": print("(%s) start" % os.getpid()) q = multiprocessing.Manager().Queue() po = multiprocessing.Pool() for i in range(2): po.apply_async(write, args=(q,)) time.sleep(2) po.apply_async(read, args=(q,)) po.close() po.join() print("(%s) end" % os.getpid())