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.')
Pool
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from multiprocessing import Pool import os, time, random
if __name__=='__main__': print('Parent process %s.' % os.getpid()) p = Pool(4) for i inrange(5): p.apply_async(long_time_task, args=(i,)) print('Waiting for all subprocesses done...') p.close() p.join() print('All subprocesses done.')
from multiprocessing import Process import os import time from multiprocessing import Pool from multiprocessing import Queue defwrite(q): print('write pid:%s', os.getpid()) for value in [1,3,4]: print('write %s', value) q.put(value) time.sleep(1) defread(q): print('read pid:%s', os.getpid()) while1: value = q.get() print('read %s', value) if __name__ == '__main__': q = Queue() pw = Process(target=write, args=(q,)) pr = Process(target=read, args=(q,)) pw.start() pr.start() pw.join() pr.terminate()