Mutex of analog to grab votes

import time, json
from multiprocessing import Process, Lock # 互斥锁
def serch(name):
time.sleep(1)
dic = json.load(open('db.txt', 'r', encoding='utf-8'))
print('%s查看到剩余票数是%s'%(name, dic['count']))
def get(name):
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 ( % name) '% S grab votes success!'
DEF Task (name , the mutex):
serch (name)
mutex.acquire () # open mutex
GET (name)
mutex.release () # Close mutex
IF the __name__ == '__main__':
the mutex = lock () # mutex instantiated for I in Range ( 10): P = process ( target = Task , args = ( 'S passers%'% i , mutex)) # applied to the child process from the parent process must pass 'mutex' otherwise the child will be re-instantiated mutex p.start ( ) # mutex is of significance only of a single process, so there are mechanisms mutex will open and close the mutex



Guess you like

Origin www.cnblogs.com/yuexijun/p/11518914.html