多进程:
import multiprocessing import time def run(name): time.sleep(2) print('hello', name) if __name__ == '__main__': for i in range(10): p = multiprocessing.Process(target=run, args=('bob %s' %i,)) p.start()
获取进程ID:
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(' ') def f(name): info(' 33[31;1mfunction f 33[0m') print('hello',name) if __name__ == '__main__': info(' 33[32;1mmain process line 33[0m') p = Process(target=f, args=('bob',)) p.start() p.join()
进程间互访:
#进程队列互访 from multiprocessing import Process, Queue def f(q): q.put([42, None, 'hello']) if __name__ == '__main__': q = Queue() p = Process(target=f, args=(q,)) p.start() print(q.get()) p.join() #使用管道实现 from multiprocessing import Process, Queue, Pipe def f(conn): conn.send([42, None, 'hello']) conn.close() if __name__ == '__main__': parent_conn, child_conn = Pipe() p = Process(target=f, args=(child_conn,)) p.start() print(parent_conn.recv()) p.join() #线程队列互访 import threading, queue def f(q): q.put([42, None, 'hello']) if __name__ == '__main__': q = queue.Queue() t = threading.Thread(target=f, args=(q,)) t.start() print(q.get()) t.join()
进程间交互之Manager:
from multiprocessing import Process, Queue, Manager import os def f(d, l): d[1] = '1' d['2'] = 2 d[0.25] = None l.append(os.getpid()) print(l) 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',d) print('l',l)