一 多进程multiprocessing
multiprocessing
is a package that supports spawning processes using an API similar to the threading
module. The multiprocessing
package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing
module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.
import multiprocessing,time def run(name): print("hello",name) time.sleep(2) if __name__ == '__main__': for i in range(10): p = multiprocessing.Process(target=run,args=('Bob %s'%i,)) p.start()
import multiprocessing,time,threading def thread_run(): print(threading.get_ident()) #线程号 def run(name): print("hello",name) t = threading.Thread(target=thread_run,) t.start() time.sleep(2) if __name__ == '__main__': for i in range(10): p = multiprocessing.Process(target=run,args=('Bob %s'%i,)) p.start()
# 在主进程里调用了info,在子进程了又调用了info,我们看看效果? # 可以看到,每一个进程都是由父进程启动的。主程序的父进程是pyCharm,子进程的父进程是主进程。 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('