多进程的基本语法

用法:使用multiprocessing模块来定义多进程

import multiprocessing  # 导入多进程模块
import time
 
 
def run(name):
    time.sleep(2)
    print('hello', name)
 
 
if __name__ == '__main__':
    p_obj = []  # 存放进程对象
    for i in range(10): #启动10个进程
        p = multiprocessing.Process(target=run, args=('bob %s' % i,))  # 生成多进程的实例
        p.start()  # 启动多进程
        p_obj.append(p)
 
    for p in p_obj:
        p.join()  # 等待进程执行结束
 
#运行输出
 
hello bob 0
hello bob 1
hello bob 2
hello bob 3
hello bob 4
hello bob 5
hello bob 6
hello bob 7
hello bob 8
hello bob 9

进程中嵌入线程

import multiprocessing,threading
 
import time
 
def thread_run():
     print(threading.get_ident())
 
def run(name):
    time.sleep(2)
    print('hello', name)
    t = threading.Thread(target=thread_run(),)  #进程中嵌入线程
    t.start()
 
 
if __name__ == '__main__':
    p_obj = []
    for i in range(10):
        p = multiprocessing.Process(target=run, args=('bob %s' %i,))
        p.start()
        p_obj.append(p)
 
    for p in p_obj:
        p.join()
 
#运行输出
 
hello bob 0
4320621376
hello bob 1
4320621376
hello bob 2
4320621376
hello bob 3
4320621376
hello bob 4
4320621376
hello bob 5
4320621376
hello bob 6
4320621376
hello bob 7
4320621376
hello bob 8
4320621376
hello bob 9
4320621376

父进程与子进程的关系

from multiprocessing import Process
import os
 
 
def info(title):
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())  #获取父进程ID
    print('process id:', os.getpid())  #获取进程ID
    print("

")
 
 
def f(name):
    info('33[31;1mcalled from child process function f33[0m') #调用info函数
    print('hello', name)
 
 
if __name__ == '__main__':
    info('33[32;1mmain process line33[0m')
    p = Process(target=f, args=('bob',))  #生成f函数的进程实例
    p.start()
    p.join()  #等待执行进程完毕
 
#运行输出

解析:可以看出每一个子进程都是由它的父进程启动的

原文地址:https://www.cnblogs.com/Cohen/p/8886300.html