#1 进程的开销大于线程 # from threading import Thread # import time # # def task(name): # print('%s is running'%name) # time.sleep(3) # print('%s is done'%name) # # if __name__ == '__main__': # t=Thread(target=task,args=('alex',)) #元祖形式 # t.start() # print('主线程') #alex is running 主进程 几乎是同时打印 # from multiprocessing import Process # import time # # def task(name): # print('%s is running'%name) # time.sleep(3) # print('%s is done'%name) # # if __name__ == '__main__': # t=Process(target=task,args=('alex',)) #元祖形式 # t.start() # print('主进程') #一定是先打印主进程 因为他要申请内存空间 将开启进程的信号发给操作系统后,操作系统要申请内存空间,让好拷贝父进程地址空间到子进程,开销远大于线程 #2同一进程内的多个线程共享进程的地址空间 ''' 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) 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) ''' #3 pid # 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()) from threading import Thread import os def work(): print('hello',os.getpid()) if __name__ == '__main__': t1=Thread(target=work) t1.start() print('主线程pid',os.getpid())