Python--day41--线程锁
1,死锁
死锁代码示例:
1 import time 2 from threading import Lock, Thread 3 4 noodle_lock = Lock() 5 fork_lock = Lock() 6 7 def eat1(name): 8 noodle_lock.acquire() 9 print('%s拿到面了'%name) 10 fork_lock.acquire() 11 print('%s拿到叉子了'%name) 12 print('%s吃面'%name) 13 fork_lock.release() 14 noodle_lock.release() 15 16 def eat2(name): 17 fork_lock.acquire() 18 print('%s拿到叉子了' % name) 19 time.sleep(1) 20 noodle_lock.acquire() 21 print('%s拿到面了'%name) 22 print('%s吃面'%name) 23 noodle_lock.release() 24 fork_lock.release() 25 26 Thread(target=eat1,args=('alex',)).start() 27 Thread(target=eat2,args=('Egon',)).start() 28 Thread(target=eat1,args=('bossjin',)).start() 29 Thread(target=eat1,args=('nezha',)).start()
运行结果:
2,线程锁只能保证同一时间只有一个线程取n值,并不能保证数据安全
3,加锁保证了n不会被多个线程操纵;加锁保证数据安全
1 import time 2 from threading import Lock,Thread 3 4 def func(lock): 5 global n 6 #加锁保证了n不会被多个线程操纵 7 #获取锁的钥匙,加锁 8 lock.acquire() 9 temp = n 10 time.sleep(0.2)#睡眠0.2s 11 n = temp -1 12 #释放锁 13 lock.release() 14 15 n = 10 16 t_lst = [] 17 lock = Lock() 18 for i in range(10): 19 t = Thread(target=func,args=(lock,)) 20 t.start() 21 t_lst.append(t) 22 23 24 for t in t_lst:t.join() 25 print(n)
运行结果: