进程与线程的区别
1、开进程的开销远大于开线程,开启进程需要单独申请内存空间
from multiprocessing import Process from threading import Thread import time def piao(name): print("%s piaoing" % name) time.sleep(2) print("%s piao end" % name) if __name__ =="__main__": # p=Process(target=piao,args=("ya",)) # p.start() t = Thread(target=piao, args=("ya",)) t.start() print("The main is end.")
2、同一进程内的多个线程共享进程地址空间,如子进程和父进程之间内存隔离
from multiprocessing import Process n=100 def task(): global n n=0 if __name__ =="__main__": p = Process(target=task,) p.start() p.join() print("The main.",n)
线程公用进程内存
from threading import Thread n=100 def task(): global n n=0 if __name__ =="__main__": p = Thread(target=task,) p.start() p.join() print("The main.",n)
3、看一下pid
主进程和子进程id不一样
import os from multiprocessing import Process,current_process def task(): #print(current_process().pid)#查看当前进程id #也可以用os.getpid()方法 print("子进程pid",os.getpid()) print("父进程pid", os.getppid()) if __name__ =="__main__": p = Process(target=task,) p.start() print("The main.",current_process().pid)
线程中pid和主进程pid一样,因线程属于主进程
from threading import Thread import os def task(): print("‘子’线程pid",os.getpid()) if __name__ =="__main__": p = Thread(target=task,) p.start() print("The main.",os.getpid())