join()方法:子进程运行完,主进程在运行
import os
import time
from multiprocessing import Process
def task():
print('%s is running,parent id is <%s>' % (os.getpid(), os.getppid()))
time.sleep(3)
print('%s is done,parent id is <%s>' % (os.getpid(), os.getppid()))
if __name__ == '__main__':
p = Process(target=task, )
p.start()
p.join() # p的进程运行完毕,再进行下面的运行
print('主', os.getpid(), os.getppid())
print(p.pid)
结果:
12736 is running,parent id is <12576>
12736 is done,parent id is <12576>
主 12576 9800
12736
多个子进程运行结束后(所用时间是sleep时间最长的子进程),再执行主进程:
import time
from multiprocessing import Process
def task(name, n):
print('%s is running' % name)
time.sleep(n)
if __name__ == '__main__':
start = time.time()
p1 = Process(target=task, args=('子进程1', 5))
p2 = Process(target=task, args=('子进程2', 3))
p3 = Process(target=task, args=('子进程3', 2))
p_l = [p1, p2, p3]
for p in p_l:
p.start()
for p in p_l:
p.join()
print('主', (time.time() - start))
结果:
子进程1 is running
子进程2 is running
子进程3 is running
主 5.232480764389038
一个子进程运行结束后再执行另一个子进程…(所用时间是所有子进程sleep累加),最后执行主进程:
import time
from multiprocessing import Process
def task(name, n):
print('%s is running' % name)
time.sleep(n)
if __name__ == '__main__':
start = time.time()
p1 = Process(target=task, args=('子进程1', 5))
p2 = Process(target=task, args=('子进程2', 3))
p3 = Process(target=task, args=('子进程3', 2))
p1.start()
p1.join()
p2.start()
p2.join()
p3.start()
p3.join()
print('主', (time.time() - start))
结果:
子进程1 is running
子进程2 is running
子进程3 is running
主 10.595051288604736
is_alive()方法、pid
import os
import time
from multiprocessing import Process
def task():
print('%s is running,parent id is <%s>' % (os.getpid(), os.getppid()))
time.sleep(2)
print('%s is done,parent id is <%s>' % (os.getpid(), os.getppid()))
if __name__ == '__main__':
p = Process(target=task, )
p.start()
print(p.is_alive())
p.join()
print('主', os.getpid(), os.getppid())
print(p.pid)
print(p.is_alive())
结果:
True
9764 is running,parent id is <7768>
9764 is done,parent id is <7768>
主 7768 9800
9764
False
terminate()方法、name
import os
import time
from multiprocessing import Process
def task():
print('%s is running,parent id is <%s>' % (os.getpid(), os.getppid()))
time.sleep(3)
print('%s is done,parent id is <%s>' % (os.getpid(), os.getppid()))
if __name__ == '__main__':
p = Process(target=task, )
p.start()
p.terminate() #关闭进程,不会立即关闭,所以is_alive立刻查看的结果可能还是存活
print(p.is_alive())
time.sleep(3)
print(p.is_alive())
print('主')
print(p.name)
结果:
True
False
主
Process-1