#!/usr/bin/env python
# encoding: utf-8
# Date: 2018/6/17
import json, time
from multiprocessing import Process, Lock
def search(name):
time.sleep(1) # 模拟网页延迟
dic = json.load(open('db.txt', 'r', encoding='utf-8'))
print('<%s>查看剩余票数(%s)' % (name, dic['count']))
def get(name):
time.sleep(1)
dic = json.load(open('db.txt', 'r', encoding='utf-8'))
if dic['count'] > 0:
dic['count'] -= 1
time.sleep(3) # 模拟网络写入数据库,还有支付
json.dump(dic, open('db.txt', 'w', encoding='utf-8'))
print('<%s> 购票成功' % name)
def task(name, mutex):
search(name) # 查票应该是并发执行
mutex.acquire()
get(name) # 购票应该是串行
mutex.release()
if __name__ == '__main__':
mutex = Lock() # 互斥锁
for i in range(10): # 模拟是个人抢票
p = Process(target=task, args=('路人%s' % i, mutex))
p.start()
# p.join() # 会把看都变成串行,代码整体受影响
db.txt
{"count": 1}