Multi-threaded review 2

1. Global lock GIL 
    has one and only one thread running at any given time- > thread is safer
 2. Thread complexity is higher, it is generally not recommended to use
 3. Used in the database thread pool, database connection pool,
 4 . Do not use a lot of threads, modify slightly more difficult 
mlock = threading.Lock ()
 5 . mutex 
    lock Acquire 
        mlock.acquire () 
    to release the lock release 
        mlock.release () 
    after lock release, the release will not occur deadlock 
    such as: open a file does not want others to modify
 6. the mlock = threading.RLock () 
    when the deadlock, the deadlock prevention reusability lock, a plurality of locking and releasing the lock can be used in the same function 

program: 
# test , Is thread safe 
import threading 

num = 0 
 def t ():
     globalNUM 
    NUM + =. 1
     Print (NUM)
 for I in Range (0,6 ): 
    D = of the threading.Thread (target = T) 
    d.start () 
    # can be sequentially output 


Import Threading 
 Import Time 

DEF func_A ():
     Print ( " a function start " ) 
    time.sleep ( 2 )
     print ( " a function end " ) 

def func_b ():
     print ( " b function start " )
    the time.sleep ( 2 )
     Print ( " b function ends " ) 

B Time = time.time () 
func_A () 
func_B () 
Print (time.time () - B Time)
 # View the number of seconds to run 

Import Threading 

_a = threading.Thread ( = target func_A) 
_b = threading.Thread (target = func_B) 
_a.start () 
_b.start () 
# start 
_a.join () 
_b.join () 
# wait 
Print (time.time () - B Time)
 # View Time 

# lock and release
 import threading
mlock = threading.Lock ()
 # create a lock, mlock name 
# mlock = threading.RLock () 
# when there is a deadlock, deadlock prevention reusable lock 
NUM = 0 
 DEF A ():
     , Ltd. Free Join NUM 
    mlock.acquire ( ) 
    # lock 
    NUM = +. 1  
    mlock.release () 
    # release lock 
    Print (NUM)
 for I in Range (10 ): 
    D = of the threading.Thread (target = A) 
    d.start ()

2020-04-12

Guess you like

Origin www.cnblogs.com/hany-postq473111315/p/12686171.html