用法:使用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('