美文网首页
python多进程

python多进程

作者: citySouth | 来源:发表于2017-05-13 13:59 被阅读0次

    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
    

    相关文章

      网友评论

          本文标题:python多进程

          本文链接:https://www.haomeiwen.com/subject/psuxxxtx.html