python basis --GIL global interpreter lock, Event events, semaphores, deadlocks, recursive lock

ps: python interpreter, there are many, the most common is C python interpreter

GIL Global Interpreter Lock:
    is an exclusive lock on GIL nature: the concurrent become serial, sacrifice efficiency to ensure the security of data

    At the same time used to prevent multiple threads in the same process of execution (multiple threads within the same process but can not be achieved in parallel to achieve concurrent)

    GIL's existence is because the memory management C python interpreter is not thread safe

    Garbage collection:

        1, the reference count

        2, clear labeling

        3, recovered generational

    Python multithreading study of the usefulness of the discussions if needed points:

        While performing computationally intensive four tasks: 10s

# 计算密集型
from multiprocessing import Process
from threading import Thread
#mport os,time
def work():
    res=0
    for i in range(100000000):
        res*=i


if __name__ == '__main__':
    l=[]
    print(os.cpu_count())  # 本机为6核
    start=time.time()
    for i in range(6):
        # p=Process(target=work) #耗时  4.732933044433594
        p=Thread(target=work) #耗时 22.83087730407715
        l.append(p)
        p.start()
    for p in l:
        p.join()
    stop=time.time()
    print('run time is %s' %(stop-start))

 

        Single-core cases:

            Open thread more to save resources

        Multi-core cases:

            Open Process: 10s

            Open Thread: 40s

        IO-intensive tasks simultaneously execute four

# IO密集型
from multiprocessing import Process
from threading import Thread
import threading
import os,time
def work():
    time.sleep(2)


if __name__ == '__main__':
    l=[]
    print(os.cpu_count()) #本机为6核
    start=time.time()
    for i in range(4000):
        p=Process(target=work) #9.001083612442017s time-consuming and more, most of the time spent on the process of creating 
        # the p-= the Thread (target = Work) # consuming 2.051966667175293s multi 
        l.append (the p-) 
        p.start () 
    for the p- in L: 
        p.join () 
    STOP = the time.time ()
     Print ( ' RUN Time IS S% ' % (Start-STOP))

 

        Single-core: open thread more provincial resources

        Multi-core: open thread more provincial resources

    

Event events:

    

from Threading Import the Event, the Thread
 Import Time 

# Mr. into an event object 
E = the Event () 


DEF Light ():
     Print ( ' red lit n ' ) 
    the time.sleep ( . 3 ) 
    e.set ()   # signaling 
    Print ( ' green light ' ) 

DEF CAR (name):
     Print ( ' % S is a red light ' % name) 
    e.wait ()   # wait signal 
    Print ( ' % S fuel door of racing ' %name)

t = Thread(target=light)
t.start()

for i in range(10):
    t = Thread(target=car,args=('伞兵%s'%i,))
    t.start()

 

 

 

Semaphore: in different areas corresponding to different points of knowledge

    Mutex: a toilet (a pit)
    semaphore: public toilet (pits bits)

from Threading Import Semaphore, the Thread
 Import Time
 Import Random 


SM = Semaphore (. 5)   # built public toilets containing a five-bit pit 

DEF Task (name): 
    sm.acquire () 
    Print ( ' % S accounted for a pit bit ' % name) 
    the time.sleep (the random.randint ( l, 3 )) 
    sm.release () 

for I in Range (40 ): 
    T = the Thread (target = Task, args = (I,)) 
    t.start ()

 

  

Deadlock:

    RLock can be continuously acquire and release the lock of the first to grab people

    Each acquire a lock body count is incremented by one

    Each time the lock release body count decrements

    As long as the lock count is not zero else can grab

class MyThread (the Thread):
     DEF run (Self):   # create a thread automatically trigger a call to the run method in the run method is equivalent to func1 func2 automatically trigger 
        self.func1 () 
        self.func2 () 

    DEF func1 (Self): 
        mutexA.acquire ( ) 
        Print ( ' % S grabbed a lock ' % the self.name)   # the self.name equivalent current_thread (). name 
        mutexB.acquire ()
         Print ( ' % S B grab lock ' % the self.name) 
        mutexB. release () 
        Print ( ' % S B lock release ' % the self.name) 
        mutexA.release () 
        Print( ' % S A lock release ' % the self.name) 

    DEF func2 (Self): 
        mutexB.acquire () 
        Print ( ' % S B grab lock ' % the self.name) 
        the time.sleep ( . 1 ) 
        mutexA.acquire ( ) 
        Print ( ' % S grabbed a lock ' % the self.name) 
        mutexA.release () 
        Print ( ' % S a lock release ' % the self.name) 
        mutexB.release () 
        Print ( ' % S B lock release ' % the self.name) 

for Iin range(10):
    t = MyThread()
    t.start()

 

 

Recursive lock:

import threading
 
 
class MyThread(threading.Thread):
 
    def run(self):
        global n1, n2
        lock.acquire()   # 加锁
        n1 += 1
        print(self.name + ' set n1 to ' + str(n1))
        lock.acquire()   # 再次加锁
        n2 += n1
        print(self.name + ' set n2 to ' + str(n2))
        lock.release()
        lock.release()
 
n1, n2 = 0, 0
lock = threading.RLock()
 
if __name__ == '__main__':
    thread_list = []
    for i in range(5):
        t = MyThread()
        t.start()
        thread_list.append(t)
    for t in thread_list:
        t.join()
    print('final num:%d ,%d' % (n1, n2))

 

Guess you like

Origin www.cnblogs.com/tulintao/p/11354459.html