Deadlock understanding of concurrent programming, recursive lock semaphore

Deadlock understanding of concurrent programming, recursive lock semaphore

1. deadlock ****

The so-called deadlock: refers to the phenomenon of two or more processes or threads in the implementation process, a result of competition for resources caused by waiting for each other, in the absence of external force, they will not be able to promote it. At this time, say the system is in deadlock state or system to produce a deadlock, which is always in the process of waiting for another process called the deadlock, deadlock is as follows

The deadlock situation: one pair several times a mutex lock

2. To access a shared resource must also have a multi-lock, but the lock is held by these different threads or processes, will lead to the release of the routine each other waiting for the other died on the card

from threading import Thread,Lock
import time
mutexA=Lock()
mutexB=Lock()

class MyThread(Thread):
    def run(self):
        self.func1()
        self.func2()
    def func1(self):
        mutexA.acquire()
        print('\033[41m%s 拿到A锁\033[0m' %self.name)

        mutexB.acquire()
        print('\033[42m%s 拿到B锁\033[0m' %self.name)
        mutexB.release()

        mutexA.release()

    def func2(self):
        mutexB.acquire()
        print('\033[43m%s 拿到B锁\033[0m' %self.name)
        time.sleep(2)

        mutexA.acquire()
        print('\033[44m%s 拿到A锁\033[0m' %self.name)
        mutexA.release()

        mutexB.release()

if __name__ == '__main__':
    
    #同时开启10个线程
    for i in range(10):
        t=MyThread()
        t.start()


#Thread-1 拿到A锁
#Thread-1 拿到B锁
#Thread-1 拿到B锁(线程1执行完b上锁以后,睡眠2s后,但此时线程2率先抢到a锁,所以等进程2的a锁解开后,才能运行进程1中的fun2的a锁运行,但此时进程2中需要b锁,但进程1中的b锁并未解开,所以产生死锁)
#Thread-2 拿到A锁

2. recursive lock

Features: mutual exclusion between more than one thread has its effect, except that the same thread can acquire multiple times for the same lock

2. The same thread locking and unlocking must be guaranteed the same number of times, other threads to be able to grab the lock

3. Semaphore

Can limit the number of concurrent threads executing common code, if the limit is the number 1, it is no different from ordinary mutex

from threading import Semaphore,current_thread,Thread
import time

s = Semaphore(2)#同一时间最大并发2个

def task():
    s.acquire()
    time.sleep(1)
    print(current_thread().name)
    s.release()
    
for i in range(10):
    Thread(target=task).start()
    
 # 注意:信号量不是用来解决安全问题的  而是用于限制最大的并发量

Guess you like

Origin www.cnblogs.com/bruce123/p/11184412.html