一、开启进程的两种方式
方式一:
from multiprocessing import Process
import time
def task(x):
print('%s is running' %x)
time.sleep(3)
print('%s is done' %x)
if __name__ == '__main__':
# Process(target=task,kwargs={'x':'子进程'})
p=Process(target=task,args=('子进程',)) # 如果args=(),括号内只有一个参数,一定记住加逗号
p.start() # 只是在操作系统发送一个开启子进程的信号
print('主')
方式二:
from multiprocessing import Process
import time
class Myprocess(Process):
def run(self):
print('%s is running'%self.name) # name是从父类(Process)继承来的
time.sleep(3)
print('%s is done'%self.name)
if __name__ == '__main__':
p=Myprocess()
p.start() #p.run()
print('主')
方式二(自定义name)
from multiprocessing import Process
import time
class Myprocess(Process):
def __init__(self,x):
super().__init__()
self.name=x
def run(self):
print('%s is running' %self.name)
time.sleep(3)
print('%s is done' %self.name)
if __name__ == '__main__':
p=Myprocess('子进程1')
p.start() #p.run()
print('主')
主要使用方式一,可以开启多个task
二、进程内存空间彼此隔离
from multiprocessing import Process
import time
x=100
def task():
global x
x=0
print('done')
if __name__ == '__main__':
p=Process(target=task)
p.start()
time.sleep(500) # 让父进程在原地等待,等了500s后,才执行下一行代码
print(x)
三、进程对象的方法或属性
1、join :主线程等待p终止(强调:是主线程处于等的状态,而p是处于运行的状态)
p.join只能join住start开启的进程,而不能join住run开启的进程 (即task)
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()
p.join() # 让父进程在原地等待,等到子进程运行完毕后,才执行下一行代码
print('主')
同时开多个进程:
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__':
p_l=[]
start_time=time.time()
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()
stop_time=time.time()
print('主',(stop_time-start_time))
2、pid 和 ppid
from multiprocessing import Process
import time
import os
def task():
print('自己的id:%s 父进程的id:%s ' %(os.getpid(),os.getppid()))
time.sleep(200)
if __name__ == '__main__':
p1=Process(target=task)
p1.start()
print('主',os.getpid(),os.getppid())
# 爹--》主--》儿子
了解:
from multiprocessing import Process,current_process
import time
def task():
print('子进程[%s]运行。。。。' %current_process().name)
time.sleep(200)
if __name__ == '__main__':
p1=Process(target=task,name='子进程1')
p1.start()
# print(p1.name)
print('主')
from multiprocessing import Process,current_process
import time
def task():
print('子进程[%s]运行。。。。' %current_process().name)
time.sleep(2)
if __name__ == '__main__':
p1=Process(target=task,name='子进程1')
p1.start()
# print(p1.is_alive())
# p1.join()
# print(p1.is_alive()) #p.is_alive():如果p仍然运行,返回True
p1.terminate()
time.sleep(1)
print(p1.is_alive())
print('主')