Python并发编程-线程锁
Posted 空林~~清风~~~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python并发编程-线程锁相关的知识,希望对你有一定的参考价值。
互斥锁-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()
以上是关于Python并发编程-线程锁的主要内容,如果未能解决你的问题,请参考以下文章