python多进程

2017-05-13  本文已影响0人  citySouth

os.fork()

只能在Linux下使用

from multiprocessing import Process
import os
import time

def sleeper(name, seconds):
   print 'starting child process with id: ', os.getpid()
   print 'parent process:', os.getppid()
   print 'sleeping for %s ' % seconds
   time.sleep(seconds)
   print "Done sleeping"


if __name__ == '__main__':
   print "in parent process (id %s)" % os.getpid()
   p = Process(target=sleeper, args=('bob', 5))
   p2 = Process(target=sleeper, args=('john', 10))
   p.start()
   p2.start()
   print "in parent process after child process start"
   print "parent process about to join child process"
   p.join()
   p2.join()
   print "in parent process after child process join" 
   print "parent process exiting with id ", os.getpid()
   print "The parent's parent process:", os.getppid()

输出结果如下:

$ python fork.py
in parent process (id 1141)
in parent process after child process start
parent process about to join child process
starting child process with id:  1142
parent process: 1141
sleeping for 5 
starting child process with id:  1143
parent process: 1141
sleeping for 10 
Done sleeping
Done sleeping
in parent process after child process join
parent process exiting with id  1141
The parent's parent process: 989
上一篇下一篇

猜你喜欢

热点阅读