美文网首页
python防遗忘复习练手之:多进程

python防遗忘复习练手之:多进程

作者: BlueCat2016 | 来源:发表于2018-02-23 14:42 被阅读0次

    os.fork()

    # coding=utf8
    
    import os
    
    if __name__ == '__main__':
        print 'current Process (%s) start ...' % (os.getpid())
        pid = os.fork()
        print pid
        if pid < 0:
            print 'error in fork'
        elif pid == 0:
            print 'I am child process (%s) and my parent process is (%s)' % (os.getpid(), os.getppid())
        else:
            print 'I(%s) created a child process (%s)' % (os.getpid(), pid)
    

    multiprocessing

    # coding=utf8
    from multiprocessing import Process
    import os
    
    
    def run_proc(name):
        print 'Child process %s (%s) Running ...' % (name, os.getpid())
    
    
    if __name__ == '__main__':
        print 'Parent process %s.' % os.getpid()
        for i in range(5):
            p = Process(target=run_proc, args=(str(i)))
            print 'Process will start.'
            p.start()
            p.join()
        print 'Process ended ...'
    

    Pool

    # coding=utf8
    from multiprocessing import Pool
    import os, time, random
    
    
    def run_task(name):
        print 'Task %s (pid = %s) is running...' % (name, os.getpid())
        # time.sleep(random.random() * 3)
        time.sleep(3)
        print 'Task %s ended.\n' % name
    
    
    if __name__ == '__main__':
        print 'Current process %s.' % os.getpid()
        p = Pool(processes=3)
        for i in range(5):
            p.apply_async(run_task, args=(i,))
    
        print 'Waiting for all subprocesses'
        p.close()
        p.join()
        print 'All subprocesses done.'
    

    相关文章

      网友评论

          本文标题:python防遗忘复习练手之:多进程

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