同步的方法基本与多线程相同。
1) Lock
当多个进程需要访问共享资源的时候,Lock可以用来避免访问的冲突。
复制代码 代码如下:
import multiprocessing
import sys
def worker_with(lock, f):
with lock:
fs = open(f,"a+")
fs.write('Lock acquired via with\n')
fs.close()
def worker_no_with(lock, f):
lock.acquire()
try:
fs = open(f,"a+")
fs.write('Lock acquired directly\n')
fs.close()
finally:
lock.release()
if name == "main":
f = "file.txt"
lock = multiprocessing.Lock()
w = multiprocessing.Process(target=worker_with, args=(lock, f))
nw = multiprocessing.Process(target=worker_no_with, args=(lock, f))
w.start()
nw.start()
w.join()
nw.join()
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8