一、在主進程下開啓線程python
from threading import Thread def work(): print('hello') if __name__ == '__main__': t=Thread(target=work) t.start() print('主線程/主進程')
執行結果以下,幾乎是t.start ()的同時就將線程開啓了,而後先打印出了hello,證實線程的建立開銷極小編程
hello 主線程/主進程
二、在主進程下開啓進程網絡
from multiprocessing import Process def work(): print('hello') if __name__ == '__main__': #在主進程下開啓子進程 p=Process(target=work) p.start() print('主線程/主進程')
執行結果以下,p.start ()將開啓進程的信號發給操做系統後,操做系統要申請內存空間,讓好拷貝父進程地址空間到子進程,開銷遠大於線程多線程
主線程/主進程 hello
一、在主進程下開啓多個線程,每一個線程都跟主進程的pid同樣操作系統
from threading import Thread import os def work(): print('hello',os.getpid()) if __name__ == '__main__': t1=Thread(target=work) t2=Thread(target=work) t1.start() t2.start() print('主線程/主進程pid',os.getpid())
執行結果線程
hello 7939 hello 7939 主線程/主進程 7939
二、開多個進程,每一個進程都有不一樣的pidcode
from multiprocessing import Process import os def work(): print('hello',os.getpid()) if __name__ == '__main__': p1=Process(target=work) p2=Process(target=work) p1.start() p2.start() print('主線程/主進程',os.getpid())
執行結果進程
主線程/主進程 7951 hello 7952 hello 7953
一、進程之間地址空間是隔離的ip
from multiprocessing import Process import os def work(): global n n=0 if __name__ == '__main__': n=100 p=Process(target=work) p.start() p.join() print('主',n)
執行結果以下,毫無疑問子進程p已經將本身的全局的n改爲了0,但改的僅僅是它本身的,查看父進程的n仍然爲100內存
主 100
二、同一進程內開啓的多個線程是共享該進程地址空間的
from threading import Thread import os def work(): global n n=0 if __name__ == '__main__': n=100 t=Thread(target=work) t.start() t.join() print('主',n)
執行結果以下, 查看結果爲0,由於同一進程內的線程之間共享進程內的數據
主 0