作用:异步修改数据时,会造成数据安全问题,子进程分别进入文件/数据库,修改数据
""" 过程: 1.导入Lock模块 2.创建Lock对象 3.Lock对象做为要锁的进程的参数 4.lock.acquire() 5.lock.release() """ from multiprocessing import Process from multiprocessing import Lock def for_fun(lock): lock.acquire() pass lock.release() if __name__ == '__main__': lock = Lock() p = Process(target=for_fun(), args=(lock, ))
# 查看、购买电影票 # 购买要设置锁,涉及到数据的修改 import time import json from multiprocessing import Process from multiprocessing import Lock def read(name): with open(file='ticket', mode='r', encoding='utf-8') as f: ret = json.load(f)['ticket'] print('%s查询,还剩%s张票' % (name, ret)) def buy(name, lock): lock.acquire() # 拿钥匙 with open(file='ticket', mode='r', encoding='utf-8') as f: ret = json.load(f) time.sleep(0.1) if ret['ticket'] > 0: ret['ticket'] -= 1 print('%s购买成功' % name) else: print('%s购买失败' % name) time.sleep(0.1) with open(file='ticket', mode='w', encoding='utf-8') as f: json.dump(ret, f) time.sleep(0.1) lock.release() # 还钥匙 if __name__ == '__main__': lock = Lock() for i in range(1, 3): p = Process(target=read, args=('tom%s' % i, )) p.start() p = Process(target=buy, args=('tom%s' % i, lock)) p.start() """ 结果: tom1查询,还剩1张票 tom2查询,还剩1张票 tom2购买成功 tom1购买失败 """