进程_锁

#共享数据,硬盘(文件),Lock --不推荐
from multiprocessing import Process,Lock
import time,json,random
import os
def search():
    dic=json.load(open(db.txt))
    print(%s 剩余票数 %s  %(os.getpid(),dic[count]))

def get():
    dic=json.load(open(db.txt))
    time.sleep(0.1) #模拟读数据的网络延迟
    if dic[count] >0:
        dic[count]-=1
        time.sleep(0.2) #模拟写数据的网络延迟
        json.dump(dic,open(db.txt,w))
        print(%s 购票成功%os.getpid())

def task(lock):
    search()
    lock.acquire()
    get()
    lock.release()
if __name__ == __main__:
    lock=Lock()
    for i in range(10): #模拟并发100个客户端抢票
        p=Process(target=task,args=(lock,))
        p.start()
#共享数据,内存 Manager,Lock  --不推荐
from multiprocessing import Process,Manager,Lock

# def task(dic,lock):
#     lock.acquire()
#     dic["count"]-=1
#     lock.release()
    
def task(dic,lock):
    with lock:
        dic["count"]-=1
    

if __name__=="__main__":
    lock=Lock()
    m=Manager()
    dict=m.dict({"count":100})
    p_list=[]
    for i in range(100):
        p=Process(target=task,args=(dict,lock))
        p_list.append(p)
        p.start()
    for p in p_list:
        p.join()
    print(dict)
    

 

进程_锁

上一篇:linux qt5安装


下一篇:RabbitMQ 在Ubuntu18.04上的安装