Python多线程-线程锁
多线程修改一份数据时需要用到线程锁,以防止数据修改出错
#-*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import threading import time num = 0 t_obj = [] lock = threading.Lock() #声明一个锁并赋给一个变量 def MyThread(n): lock.acquire() #给线程加锁 global num time.sleep(0.5) num +=1 lock.release() #释放给线程锁 for i in range(20): t = threading.Thread(target=MyThread,args=(i,)) t.start() t_obj.append(t) for t in t_obj: t.join() print("num:",num)
递归锁
递归锁就是锁中有锁,一把锁套着一把锁
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import threading num = 0 num2 = 0 lock = threading.RLock() #声明一个递归锁 def Lock_1(): print("---This is Lock_1---") lock.acquire() global num num += 1 lock.release() return num def Lock_2(): print("---This is Lock_2---") lock.acquire() global num2 num2 += 1 lock.release() return num2 def Lock_3(): lock.acquire() print("---This is Lock_3---") Run_Lock_1 = Lock_1() print("---Between Lock_1 and Lock_2---") Run_Lock_2 = Lock_2() lock.release() print(Run_Lock_1,Run_Lock_2) for i in range(10): t = threading.Thread(target=Lock_3) t.start() while threading.active_count() != 1: print(threading.active_count()) else: print("---All Thread Have Done---") print(num,num2)