【Python】互斥锁与 抢票程序

# 互斥锁   把多个并发处理资源的进程变成串行
# 互斥锁与join 的区别:
# join 把代码整体变成串行

# from multiprocessing import Process, Lock
# # import time
# #
# #
# # def task(name, mutex):
# # mutex.acquire() # 拿锁
# # print('%s 1' % name)
# # time.sleep(1)
# # print('%s 2' % name)
# # time.sleep(1)
# # print('%s 3' % name)
# # time.sleep(1)
# # mutex.release() # 解锁
# #
# #
# # if __name__ == '__main__':
# # mutex = Lock()
# # for i in range(3):
# # p = Process(target=task, kwargs={'name': '进程%s' % i, 'mutex': mutex})
# # p.start()

# 抢票系统
import time, json
from multiprocessing import Process, Lock

# data = {'count':3}
# json.dump(data, open('db.txt', 'w', encoding='utf-8'))

def search(name, mutex):
time.sleep(1)
dic = json.load(open('db.txt', 'r', encoding='utf-8'))
print('<%s> 查看剩余票数 [%s]' % (name, dic['count']))
get(name, mutex)


def get(name, mutex):
mutex.acquire()
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)
mutex.release()


def task(name):
search(name)
get(name)


if __name__ == '__main__':
mutex = Lock()
for i in range(10):
p = Process(target=search, kwargs={'name': '路人%s' % i, 'mutex': mutex})
p.start()
posted @ 2018-08-26 17:46  caya  阅读(143)  评论(0编辑  收藏  举报