Lock process _

# Share data, hard disk (file), Lock - not recommended 
from multiprocessing Import Process, Lock
 Import Time, json, Random
 Import os
 DEF Search (): 
    dic = the json.load (Open ( ' db.txt ' ))
     Print ( ' % remaining votes S S% ' % (os.getpid (), DIC [ ' COUNT ' ])) 

DEF GET (): 
    DIC = the json.load (Open ( ' db.txt ' )) 
    the time.sleep ( 0.1) # analog read data latency network 
    IF DIC [ ' COUNT' ]> 0: 
        DIC [ ' COUNT ' ] - =. 1 
        the time.sleep ( 0.2) # analog network delaying the write data 
        The json.dump (DIC, Open ( ' db.txt ' , ' W ' ))
         Print ( ' % s purchase success ' % os.getpid ()) 

DEF Task (Lock): 
    Search () 
    lock.acquire () 
    GET () 
    lock.release () 
IF  the __name__ == ' __main__ ' : 
    Lock = Lock ()
     forI in Range (10): # simulate concurrent client 100 grab votes 
        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)
    

 

Guess you like

Origin www.cnblogs.com/hapyygril/p/12589717.html
Recommended