python 锁
Posted wt7018
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 锁相关的知识,希望对你有一定的参考价值。
作用:异步修改数据时,会造成数据安全问题,子进程分别进入文件/数据库,修改数据
""" 过程: 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() lock.acquire 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购买失败 """
以上是关于python 锁的主要内容,如果未能解决你的问题,请参考以下文章