Locks, semaphores

# Module: Lock 
# import method: Import from multiprocessing Process, Lock 
# module Method: 
    L = Lock ()
    l.acquire ()     # resource lock accessed 
    () l.release     # release lock 
# use: general part of the code that needs to access the resources of the lock to release the lock, but the novice may contain the entire first section of the program


# ########## simulation program to grab votes 
from multiprocessing Import Process, Lock
 Import Time
 # when making buying, among multiple processes there may be a process, although the first first arrived, but just time slice runs out, which will make the time to buy is not necessarily the first to arrive get a ticket 
# unlocked, it is possible to open the file when another process also has the file open, leading to buy a ticket the results of the process are not saved to be used by another process that may cause more than one person to buy a ticket to a successful case 
DEF the Check (i):
    with open("residue") as f:
        COUNT = int (reached, f.read ())          # when document reading is a string type, it is necessary to Integer type judgment 
        IF COUNT> 0:
             Print ( " first found the individual {I} to {} votes " .format ( i, COUNT))
         the else :
             Print ( " has no ticket ." )

DEF Purchase (I, L):
     # perform a locking operation 
    l.acquire ()
    with open("residue") as f:
        count = int(f.read())
        the time.sleep ( 0.1 )
     IF COUNT> 0:
         Print ( " first personal buy the tickets {} " .format (I))
        COUNT -. 1 =
     the else :
         Print ( " \ 033 [31M of individuals buy tickets {} \ 033 [1M " .format (I))
    the time.sleep ( 0.1)   # refers to the buying tickets, the tickets available rewritable database write time delay 
    with Open ( " Residue " , ' W ' ) AS F:
        f.write (STR (COUNT))   # written to the file needs to be written in the form of a string of the file, it is necessary to be cast to integer type string type 
    l.release ()

IF  __name__ == " __main__ " :
     # multiple processes are checked 
    for i in the Range (1, 10 ):
        p=Process(target=check,args=(i+1,))
        p.start()
    # Plurality of processes performed ticket 
    # to instantiate objects Lock 
    l = Lock ()
     # again l as to pass in parameters 
    for I in Range (1,10 ):
        p=Process(target=purchase,args=(i+1,l))
        p.start()
        
        
        
        
# ########## Bank of principle access money 
from multiprocessing Import Process, Value, Lock
 Import Time


DEF get_money (NUM, L): # withdrawals 
    l.acquire () # take away the keys, locked the door and not allow others to come in 
    for i in the Range (100 ):
        num.value -= 1
        print(num.value)
        time.sleep(0.01)
    l.release () # also key to open the door, allow others to come in

def put_money(num,l):# 存钱
    l.acquire()
    for i in range(100):
        num.value += 1
        print(num.value)
        time.sleep(0.01)
    l.release()

if __name__ == '__main__':
    num = Value('i',100)
    l = Lock()
    p = Process(target=get_money,args=(num,l))
    p.start()
    p1 = Process(target=put_money, args=(num,l))
    p1.start()
    p.join()
    p1.join()
    print(num.value)

 

 

 

# Module: Semaphore 
# import method: Import from multiprocessing Process, Semaphore 
# modular approach: 
    sem = Semaphore (i)         # i is a (room) allows the i-th process enters 
    sem.acquire ()             # to access the resource lock 
    sem .release ()             # release lock 
# use method: similar to lock 
# semaphores and locks similar: the popular understanding, the lock mechanism is a process can only go in one room, while the semaphore is a mechanism to allow the i-th process into the room 
# semaphore and lock difference: semaphore mechanism more than a locking mechanism counter, this counter is used to record the current remaining few keys. 
                 When the counter is 0, indicating there is no key, this time acquire () is blocked.
                 For counter, every acquire time, the internal counter is decremented by 1, Release time, the counter is increased by one


from multiprocessing import Process,Semaphore
import time
import random

DEF FUNC (I, SEM):
     # start Semaphore implementation 
    sem.acquire ()
     Print ( " first into the individual {} " .format (I))
    the time.sleep (the random.randint ( 3,5 ))
     Print ( " first personal exit {} " .format (I))
     # end semaphore implementation 
    sem.release ()



IF  __name__ == " __main__ " :
     # allowed to count a process to access the resource 
    count = 5 
    sem = Semaphore (count)
     for i in the Range (10 ):
        p=Process(target=func,args=(i,sem))
        p.start()

 

Guess you like

Origin www.cnblogs.com/god-for-speed/p/11719087.html