文章目录
守护进程 daemon
主进程设置子进程为守护进程之后,守护进程会在主进程执行结束后终止,守护进程内无法开启子进程
from multiprocessing import Process
import time
def run(name): # 定义了run函数
print('%s is running' % name)
time.sleep(3)
if __name__ == '__main__':
p1 = Process(target=run, args=('小明',))
p1.daemon = True # 一定要放在start前面
p1.start()
print('主进程')
# 主进程
再来看:
def test1():
print(123)
time.sleep(1)
print('end 123')
def test2():
print(456)
time.sleep(1)
print('end 456')
if __name__ == '__main__':
p1 = Process(target=test1)
p2 = Process(target=test2)
p1.daemon = True
p1.start()
p2.start()
print('主进程')
# 主进程
# 456
# end 456
主进程执行完之后,子进程p1为守护进程还没来得及开启就结束了。
守护进程内开子进程报错:
from multiprocessing import Process
import time
def test(n):
print('守护进程内开子进程')
time.sleep(n)
print('执行完毕')
def run(name):
print('%s is running' % name)
time.sleep(3)
p2 = Process(target=test, args=(3,))
p2.start()
if __name__ == '__main__':
p1 = Process(target=run, args=('小明',))
p1.daemon = True
p1.start()
p1.join()
print('主进程')
# 结果:守护进程内开子进程报错
小明 is running
AssertionError: daemonic processes are not allowed to have children
主进程
互斥锁 Lock
多个进程之间不共享数据,但是共享一套文件系统,多个进程共享的时候会产生竞争资源,发生错乱。互斥锁就是进行加锁处理,保证数据不错乱,原理是把并发改成了串行,降低了效率。
from multiprocessing import Process, Lock
import time
def test(name):
print('%s is running' % name)
time.sleep(2)
print('%s is done' % name)
if __name__ == '__main__':
for i in range(3):
p = Process(target=test, args=(i,))
p.start()
# 0 is running
# 1 is running
# 2 is running
# 2 is done
# 1 is done0 is done
加锁之后,mutex = Lock(),运行时间长了
from multiprocessing import Process, Lock
import os, time
def test(name,mutex):
mutex.acquire()
print('%s is running' % name)
time.sleep(2)
print('%s is done' % name)
mutex.release()
if __name__ == '__main__':
mutex = Lock()
for i in range(3):
p = Process(target=test, args=(i, mutex)) # 主进程的锁传递给子进程,所有子进程用同一把锁
p.start()
# 0 is running
# 0 is done
# 2 is running
# 2 is done
# 1 is running
# 1 is done