递归锁

线程死锁和递归锁

在线程间共享多个资源的时候,如果两个线程分别占有一部分资源并且同时等待对方的资源,就会造成死锁,因为系统判断这部分资源正在使用,所有这两个线程在无外力作用下将一直等待下去。

import threading
import time

class MyThread(threading.Thread):

    def actionA(self):
        A.acquire()
        print(self.name, 'got A', time.ctime())
        time.sleep(2)

        B.acquire()
        print(self.name, 'got B', time.ctime())
        time.sleep(1)

        B.release()
        A.release()
    def actionB(self):
        B.acquire()
        print(self.name, 'got B', time.ctime())
        time.sleep(2)

        A.acquire()
        print(self.name, 'got A', time.ctime())
        time.sleep(1)

        A.release()
        B.release()

    def run(self):
        self.actionA()
        self.actionB()

if __name__ == '__main__':
    A = threading.Lock()
    B = threading.Lock()
    L = []

    for i in range(5):
        t = MyThread()
        t.start()
        L.append(t)

    for i in L:
        i.join()

    print('ending...')
import threading
import time

class MyThread(threading.Thread):

    def actionA(self):
        r_lock.acquire()
        print(self.name, 'got A', time.ctime())
        time.sleep(2)

        r_lock.acquire()
        print(self.name, 'got B', time.ctime())
        time.sleep(1)

        r_lock.release()
        r_lock.release()
    def actionB(self):
        r_lock.acquire()
        print(self.name, 'got B', time.ctime())
        time.sleep(2)

        r_lock.acquire()
        print(self.name, 'got A', time.ctime())
        time.sleep(1)

        r_lock.release()
        r_lock.release()

    def run(self):
        self.actionA()
        self.actionB()

if __name__ == '__main__':
    # A = threading.Lock()
    # B = threading.Lock()
    # 递归锁
    r_lock = threading.RLock()

    L = []

    for i in range(5):
        t = MyThread()
        t.start()
        L.append(t)

    for i in L:
        i.join()

    print('ending...')

你可能感兴趣的:(python)