Python队列、进程间通信、线程案例队列、进程间通信、线程案例
进程互斥锁进程互斥锁
多进程同时抢购余票
# 并发运行,效率高,但竞争写同一文件,数据写入错乱
# data.json文件内容为 {"ticket_num": 1}
import json
import time
from multiprocessing import Process
def search(user):
with open('data.json', 'r', encoding='utf-8') as f:
dic = json.load(f)
print(f'用户{user}查看余票,还剩{dic.get("ticket_num")}...')
def buy(user):
with open('data.json', 'r', encoding='utf-8') as f:
dic = json.load(f)
time.sleep(0.1)
if dic['ticket_num'] > 0:
dic['ticket_num'] -= 1
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(dic, f)
print(f'用户{user}抢票成功!')
else:
print(f'用户{user}抢票失败')
def run(user):
search(user)
buy(user)
if __name__ == '__main__':
for i in range(10): # 模拟10个用户抢票
p = Process(target=run, args=(f'用户{i}', ))
p.start()
使用锁来保证数据安全
# data.json文件内容为 {"ticket_num": 1}
import json
import time
from multiprocessing import Process, Lock
def search(user):
with open('data.json', 'r', encoding='utf-8') as f:
dic = json.load(f)
print(f'用户{user}查看余票,还剩{dic.get("ticket_num")}...')
def buy(user):
with open('data.json', 'r', encoding='utf-8') as f:
dic = json.load(f)
time.sleep(0.2)
if dic['ticket_num'] > 0:
dic['ticket_num'] -= 1
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(dic, f)
print(f'用户{user}抢票成功!')
else:
print(f'用户{user}抢票失败')
def run(user, mutex):
search(user)
mutex.acquire() # 加锁
buy(user)
mutex.release() # 释放锁
if __name__ == '__main__':
# 调用Lock()类得到一个锁对象
mutex = Lock()
for i in range(10): # 模拟10个用户抢票
p = Process(target=run, args=(f'用户{i}', mutex))
p.start()