方式一
在windows系统上,开启子进程的操作必须放到:
if name == 'main':的子代码中
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__':
p = Process(target=task, args=('子进程...',))
p.start()
print('主进程...')
方式二
from multiprocessing import Process
import time
class MyProcess(Process):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
print('%s is running...' % self.name)
time.sleep(3)
print('%s is done' % self.name)
if __name__ == '__main__':
p = MyProcess('子进程...')
p.start()
print('主进程...')
join方法
join:让主进程在原地等待,等待子进程运行完毕,不会影响子进程的执行
from multiprocessing import Process
import time
def task(name,n):
print('%s is running' %name)
time.sleep(n)
print('%s is done' %name)
if __name__ == '__main__':
"""
p1=Process(target=task,args=('子1',1))
p2=Process(target=task,args=('子2',2))
p3=Process(target=task,args=('子3',3))
start=time.time()
p1.start()
p2.start()
p3.start()
p3.join()
p1.join()
p2.join()
print('主',(time.time()-start))
"""
start=time.time()
p_l=[]
for i in range(1,4):
p = Process(target=task, args=('子%s' %i, i))
p_l.append(p)
p.start()
for p in p_l:
p.join()
print('主', (time.time() - start))
验证:进程之间内存空间相互隔离
from multiprocessing import Process
n=100
def task():
global n
n=0
if __name__ == '__main__':
p=Process(target=task)
p.start()
p.join()
print(n)
打印 n 发现 n 的值还是为100 ,说明子进程内的更改并不会影响到主进程的内存空间,也就是说明了进程之间的内存空间相互隔离
进程对象其他相关的属性或方法
1. 进程pid:每一个进程在操作系统内都有一个唯一的id号,称之为pid
from multiprocessing import Process,current_process
import time
def task():
print('%s is running' %current_process().pid)
time.sleep(30)
print('%s is done' %current_process().pid)
if __name__ == '__main__':
p=Process(target=task)
p.start()
print('主',current_process().pid)
上下两种不同的写法
from multiprocessing import Process,current_process
import time,os
def task():
print('%s is running 爹是:%s' %(os.getpid(),os.getppid()))
time.sleep(30)
print('%s is done 爹是:%s' %(os.getpid(),os.getppid()))
if __name__ == '__main__':
p=Process(target=task)
p.start()
print('主:%s 主他爹:%s' %(os.getpid(),os.getppid()))
2. 进程对象其他相关的属性或方法
from multiprocessing import Process,current_process
import time,os
def task():
print('%s is running 爹是:%s' %(os.getpid(),os.getppid()))
time.sleep(30)
print('%s is done 爹是:%s' %(os.getpid(),os.getppid()))
if __name__ == '__main__':
p=Process(target=task,name='子进程1')
p.start()
# print(p.name)
p.terminate()
# time.sleep(0.1)
print(p.is_alive())
print('主:%s 主他爹:%s' %(os.getpid(),os.getppid()))