python with thread lock

Threading Import 
Import Time 

NUM = 0   # multiple threads can read and write global variables, data transfer 
the mutex = threading.RLock () # Create a lock 


class myThread (of the threading.Thread): 
    DEF RUN (Self): 
        Global NUM 
        with the mutex: # role with RLock is equivalent to automatically acquire and release the lock (resources) 
            for i in the Range ( 1000 ): # lock period, other threads can not work 
                NUM + = 1 
        Print (NUM) 


MyThread = [] 

for i in the Range ( 5 ): 
    T = myThread () 
    t.start () 
    mythread.append (T)
for t in mythread:
    t.join()
print("ceshi")

Another way, without transfer of the threading.Thread, direct manipulation properties:

Import Threading
 Import Time 

NUM = 0   # global variables multiple threads can read and write data transfer 

class myThread (): 
    the mutex = threading.RLock ()   # Create a class attribute lock 

    DEF RUN (Self):
         Global NUM 
        with the mutex:   # with RLock equivalent effect automatically acquiring and releasing locks (resources) 
            for i in the Range (1000):   # lock period, other threads can not work 
                NUM + 1 = Print (NUM) 
MyThread = [] 
t = myThread () 
t. RUN () Print ( " ceshi
        


")

 

According to Web search integration:

Reference: https://blog.csdn.net/houyanhua1/article/details/78233519

 

Guess you like

Origin www.cnblogs.com/weilaibuxiangshuo/p/11627840.html