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

2018-02-23  本文已影响0人  BlueCat2016

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.'
上一篇下一篇

猜你喜欢

热点阅读