Python并发编程-线程锁

时间:2022-03-13 18:01:33

互斥锁-Lock

#多线程中虽然有GIL,但是还是有可能产生数据不安全,故还需加锁
from threading import Lock, Thread #互斥锁
import time
def eat1(lock):
    global n
    lock.acquire()
    temp =n
    time.sleep(0.2)
    n = temp - 1
    lock.release()

if __name__ == '__main__':
    n = 10
    t_lst = []
    lock = Lock()
    for i in range(10):
        t = Thread(target=eat1,args=(lock,))
        t.start()
        t_lst.append(t)
    for t in t_lst: t.join()
    print(n)

递归锁-RLOCK

from threading import RLock, Thread #RLock递归锁
import time

noddle_lock =fork_lock =RLock() #必须这么写,不能分开两行
# fork_lock = RLock()
def eat1(name):
    noddle_lock.acquire()
    print('%s拿到面条了'%name)
    fork_lock.acquire()
    print('%s拿到叉子了'%name)
    print('%s吃面了'%name)
    fork_lock.release()
    noddle_lock.release()

def eat2(name):
    fork_lock.acquire()
    print('%s拿到叉子了'%name)
    time.sleep(1)
    noddle_lock.acquire()
    print('%s拿到面条了'%name)
    print('%s吃面了'%name)
    noddle_lock.release()
    fork_lock.release()

Thread(target=eat1,args=('alex',)).start()
Thread(target=eat2,args=('egon',)).start()
Thread(target=eat1,args=('bossjin',)).start()
Thread(target=eat2,args=('nezha',)).start()