与线程不同,进程没有任何共享状态,进程修改的数据,改动仅限于该进程内,多进程间的资源是相互独立的,多进程是并行的
多进程的实现与多线程类似
注意:在windows中Process()必须放到# if __name__ == '__main__':下
import multiprocessing,time
def run():
time.sleep(1)
print('hello',time.ctime())
if __name__ == '__main__':
l=[]
for i in range(3):
t=multiprocessing.Process(target=run)
l.append(t)
t.start()
for t in l:
t.join()
print('end...')
'''
hello Fri Apr 20 22:08:32 2018
hello Fri Apr 20 22:08:32 2018
hello Fri Apr 20 22:08:32 2018
end...
'''
用类实现
import multiprocessing,time
class Myprocess(multiprocessing.Process):
def run(self):
time.sleep(1)
print('hello',self.name,time.ctime())
if __name__ == '__main__':
l=[]
for i in range(3):
t=Myprocess()
l.append(t)
t.start()
for t in l:
t.join()
print('end...')
'''
hello Myprocess-1 Fri Apr 20 22:16:41 2018
hello Myprocess-2 Fri Apr 20 22:16:42 2018
hello Myprocess-3 Fri Apr 20 22:16:42 2018
end...
'''
进程间的数据是相互独立的
import multiprocessing,time,os
n=100
def foo():
global n
n=0
print('subprocess n is',n)
if __name__ == '__main__':
t=multiprocessing.Process(target=foo)
t.start()
t.join()
print('main process n is',n)
'''
subprocess n is 0
main process n is 100
'''
守护进程
import multiprocessing,time
class Myprocess(multiprocessing.Process):
def run(self):
time.sleep(1)
print('hello',self.name,time.ctime())
if __name__ == '__main__':
l=[]
for i in range(3):
t=Myprocess()
l.append(t)
t.daemon=True
t.start()
print('end...')
'''
end...
'''
注意:进程之间是互相独立的,主进程代码运行结束,守护进程随即终止
#主进程代码运行完毕,守护进程就会结束
from multiprocessing import Process
from threading import Thread
import time
def foo():
print(123)
time.sleep(1)
print("end123")
def bar():
print(456)
time.sleep(3)
print("end456")
if __name__ == '__main__':
p1=Process(target=foo)
p2=Process(target=bar)
p1.daemon=True
p1.start()
p2.start()
print("main-------") #打印该行则主进程代码结束,则守护进程p1应该被终止,可能会有p1任务执行的打印信息123,因为主进程打印main----时,p1也执行了,但是随即被终止
'''
main-------
456
end456
'''
PID
import multiprocessing,time,os
def info(title):
print('title:',title)
print('Parent process ID:',os.getppid())#打印父进程ID
print('Process ID:',os.getpid())#打印现在进程ID
def f():
info('main process')
print('Ok...')
if __name__ == '__main__':
f()
t=multiprocessing.Process(target=info,args=('subprocess',))
print('-'*20)
time.sleep(2)
t.start()
t.join()
print('end....')
'''
title: main process
Parent process ID: 4676 #因为使用pycharm运行,故pycharm的进程ID为父进程,如果用解释器则没有父进程ID
Process ID: 2980
Ok...
--------------------
title: subprocess
Parent process ID: 2980
Process ID: 2116
end....
'''