3.3.1 进程操作

多进程的第一个示例

import multiprocessing
import threading
import time

def thread_run():
    print(threading.get_ident())    #子线程输出线程ID号

def run(name):
    time.sleep(2)
    print('Hello ', name)
    t = threading.Thread(target=thread_run, )
    t.start()    #每个进程启动一个子线程


if __name__ == '__main__':
    for i in range(10):    #启动10个进程
        p = multiprocessing.Process(target=run, args=('John', ))
        #多进程的语法
        p.start()

结果

multiProcess_result

下面的示例可以很清晰的展示父进程和子进程的关系

from multiprocessing import Process
import os

def info(title):
    print(title)
    print('module name: ', __name__)
    print('parent process: ', os.getppid())    #输出parent process id父进程ID
    print('process id: ', os.getpid())    #输出当前ID
    print('\n\n')

def f(name):
    info('\033[31;1mFunction f\033[0m')
    print('Hello', name)


if __name__ == '__main__':
    info('\033[32;1mMain process line\033[0m')
    # p = Process(target=f, args=('John', ))    #多进程执行f()函数
    # p.start()

这里我们多运行几次,看看结果

一次

Main process line
module name:  __main__
parent process:  10056
process id:  11512

二次

Main process line
module name:  __main__
parent process:  10056
process id:  14108

三次

Main process line
module name:  __main__
parent process:  10056
process id:  5236

以上结果,发现每次父进程ID都是一样的,10056,这个10056是谁呢?答案在系统的任务管理器里

ParentID

可以看到,10056进程就是Pycharm本身的进程。将该示例最后两行的注释去掉,我们接着往下看:

from multiprocessing import Process
import os

def info(title):
    print(title)
    print('module name: ', __name__)
    print('parent process: ', os.getppid())    #输出parent process id父进程ID
    print('process id: ', os.getpid())    #输出当前ID
    print('\n\n')

def f(name):
    info('\033[31;1mFunction f\033[0m')
    print('Hello', name)


if __name__ == '__main__':
    info('\033[32;1mMain process line\033[0m')
    p = Process(target=f, args=('John', ))    #多进程执行f()函数
    p.start()

结果1

Main process line
module name:  __main__
parent process:  10056
process id:  14852



Function f
module name:  __mp_main__
parent process:  14852
process id:  10376



Hello John

结果2

Main process line
module name:  __main__
parent process:  10056
process id:  13988



Function f
module name:  __mp_main__
parent process:  13988
process id:  9812



Hello John

结果3

Main process line
module name:  __main__
parent process:  10056
process id:  12836



Function f
module name:  __mp_main__
parent process:  12836
process id:  8528



Hello John

这里看出了什么?每一条结果中,Function f的父进程ID与Main process line中的进程ID是一致的。

这个结果说明,每个子进程都是由父进程启动的。

猜你喜欢

转载自www.cnblogs.com/infinitecodes/p/12126678.html