"""
每一个进程都有自己独立的空间,多进程操作同一块数据时,必须加锁处理,否则会导致数据错误
加锁会把程序变成串行,效率变低
"""
from multiprocessing import Process, Lock
import time
import os
def demo_one():
"""查票"""
with open("data.txt", "r") as f:
num = int(f.read())
return num
def demo_two(lock):
"""购票"""
n = demo_one()
print("%s end,结束查询余票:%d\n" % (str(os.getpid()), n))
lock.acquire()
if n:
n -= 1
with open("data.txt", "w") as f:
n = 0
f.write(str(n))
print("%s 购票成功\n" % os.getpid())
else:
print("%s 失败\n" % os.getpid())
lock.release()
def buy(lock, start):
demo_two(lock)
print("end time %d!!!!!!!!!!!!!!!" % (time.time() - start))
if __name__ == '__main__':
start = time.time()
p_list = []
lock = Lock()
for i in range(30):
p = Process(target=buy, args=(lock, start))
p.start()
p_list.append(p)
print("main----------------------------")
07-03
1814