pid = os.fork() if pid == 0: print('2\ti\'m son %d, my father is %d' % (os.getpid(), os.getppid())) else: print('3\ti %d just create a son %d.' % (os.getpid(), pid))
print('4\t%d' % os.getppid())
我们通过上述代码的输出来讨论这个问题:
1 2 3 4 5
1 23714 3 i 23714 just create a son 23721. 4 5408 2 i'm son 23721, my father is 23714 4 23714
if __name__ == '__main__': print('Parent process %s.' % os.getpid()) p = Pool(4) for i in range(5): p.apply_async(long_time_task, args=(i,)) print('Waiting for all subprocesses done...') p.close() p.join() print('All subprocesses done.')
代码输出如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
Parent process 7240. Waiting for all subprocesses done... Run task 0 (7247)... Run task 1 (7248)... Run task 2 (7249)... Run task 3 (7250)... Task 3 runs 0.11 seconds. Run task 4 (7250)... Task 4 runs 0.74 seconds. Task 0 runs 1.11 seconds. Task 1 runs 2.14 seconds. Task 2 runs 2.25 seconds. All subprocesses done.