进程间的资源是不会共享的
from multiprocessing import Process
import os
number = 0
def work1(*args):
global number
for i in range(5):
number += 1
print(F'子进程1{args}执行任务pid={os.getpid()}-------')
print(f'进程{os.getpid()}',number)
def work2(**kwargs):
global number
for i in range(6):
number += 1
print(F'子进程2{kwargs}执行任务,pid={os.getpid()}-------')
print(f'进程{os.getpid()}', number)
if __name__ == '__main__':
p1 = Process(target=work1,args=('小静',18))
p2 = Process(target=work2,kwargs={'小明':22})
p1.start()
p2.start()
p1.join()
p2.join()
print(F'主进程{os.getpid()}',number)
运行结果:
子进程1('小静', 18)执行任务pid=7752-------
子进程1('小静', 18)执行任务pid=7752-------
子进程1('小静', 18)执行任务pid=7752-------
子进程1('小静', 18)执行任务pid=7752-------
子进程1('小静', 18)执行任务pid=7752-------
进程7752 5
子进程2{'小明': 22}执行任务,pid=2220-------
子进程2{'小明': 22}执行任务,pid=2220-------
子进程2{'小明': 22}执行任务,pid=2220-------
子进程2{'小明': 22}执行任务,pid=2220-------
子进程2{'小明': 22}执行任务,pid=2220-------
子进程2{'小明': 22}执行任务,pid=2220-------
进程2220 6
主进程5508 0
可以发现执行完成后,子进程1的number为5,子进程2number为6,主进程的number还是0,因为各进程间资源不共享;
进程操作共同资源时也会引起资源竞争
当进程操作共同资源时也会引起资源竞争
from multiprocessing import Process
import os
def work1():
with open('file2.txt', 'a', encoding='utf8') as f:
for i in range(3):
print(F'进程pid{os.getpid()}正在第{i}次写入')
f.write('java-')
def work2():
with open('file2.txt', 'a', encoding='utf8') as f:
for i in range(2):
print(F'进程pid{os.getpid()}正在第{i}次写入')
f.write('python-')
def main():
p1 = Process(target=work1)
p2 = Process(target=work2)
p1.start()
p2.start()
p1.join()
p2.join()
if __name__ == '__main__':
main()
运行结果:
java-java-java-ython-python-
可见一起打开关闭时也会资源竞争,造成文件写入覆盖;
使用锁解决资源竞争问题:
注意使用锁的位置,并且锁需要以参数形式传递,因为每个进程需要单独加锁;
from multiprocessing import Process,Lock
import os
def work1(meta):
meta.acquire()
with open('file3.txt', 'a', encoding='utf8') as f:
for i in range(3):
print(F'进程pid{os.getpid()}正在第{i}次写入')
f.write('java-')
meta.release()
def work2(meta):
meta.acquire()
with open('file3.txt', 'a', encoding='utf8') as f:
for i in range(2):
print(F'进程pid{os.getpid()}正在第{i}次写入')
f.write('python-')
meta.release()
def main():
meta = Lock()
p1 = Process(target=work1,args=(meta,))
p2 = Process(target=work2,args=(meta,))
p1.start()
p2.start()
p1.join()
p2.join()
if __name__ == '__main__':
main()
运行结果:
java-java-java-python-python-