1、multiprocessing简介
multiprocessing模块提供本地和远程并发性,通过使用子进程而不是线程来有效地避开全局解释器锁。由于这个原因,多处理模块允许程序员在给定的机器上充分利用多个处理器。它在Unix和Windows上运行。
2、进程的创建
2.1、创建一个进程
import multiprocessing,time def run(name): time.sleep(2) print("hello", name) if __name__ == "__main__": p = multiprocessing.Process(target=run, args=('bob',)) p.start() p.join()
2.2、创建多个进程
import multiprocessing,time def run(name): time.sleep(2) print("hello", name) if __name__ == "__main__": for i in range(10): p = multiprocessing.Process(target=run, args=('bob %s' % i,)) p.start() # p.join()
2.3、进程中创建线程
import multiprocessing,time,threading def thread_run(): print("threading id :%s" %threading.get_ident()) 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): p = multiprocessing.Process(target=run, args=('bob %s' % i,)) p.start()
2.4、获取进程id
from multiprocessing import Process import os def info(title): print(title) print('module name:', __name__) print('parent process:', os.getppid()) print('process id:', os.getpid()) print(" ") def f(name): info('