抢票是并发执行
多个进程可以访问同一个文件
多个进程共享同一文件,我们可以把文件当数据库,用多个进程模拟多个人执行抢票任务
db.txt
{"count": 1}
并发运行,效率高,但竞争写同一文件,数据写入错乱,只有一张票,都卖成功给了10个人
#文件db.txt的内容为:{"count":1}
#注意一定要用双引号,不然json无法识别
from multiprocessing import Process
import time
import json
class Foo(object):
def search(self, name):
with open("db.txt", "r") as f_read:
dic = json.load(f_read)
time.sleep(1) # 模拟读数据的网络延迟
print("用户 查看剩余票数为 [%s]" % (name, dic["count"]))
def get(self, name):
with open("db.txt", "r") as f_read:
dic = json.load(f_read)
if dic["count"] > 0:
dic["count"] -= 1
time.sleep(1) # 模拟写数据的网络延迟
with open("db.txt", "w") as f_writ