import threading import time import random """ 线程锁:当有一个数据有多个线程都可以对其进行修改的时候,任何一个线程 改变它都会被其他线程造成影响,如果我们某一个线程在使用完之前,其他线程 不能对其修改,就需要对这个线程增加一个线程锁 """ count = 0 def get_money(money): global count money += money money += money money -= money #创建一个线程锁对象 lock = threading.Lock() def lock_thread(money): # thread1 thread2 # acquire捕获 #加锁 lock.acquire() time.sleep(random.randint(1,3)) print('当前线程为',threading.current_thread().name) get_money(money) time.sleep(random.randint(1, 3)) print('当前线程为', threading.current_thread().name) # 解锁 lock.release() #创建线程的参数为一个元组类型 [1,2,3] # 主线程 开辟一个分线程 thread1 = threading.Thread(target=lock_thread,name='thread1',args=(1000,)) thread2 = threading.Thread(target=lock_thread,name='thread2',args=(2000,)) thread1.start()#2 thread2.start()#3 print('hello world') # join注重的整体,线程1没有执行完,线程2不能执行 # lock注重的是局部,某一个变量没有用完,其他线程不能使用 thread1.join() thread2.join()
线程锁
最新推荐文章于 2023-06-28 09:52:25 发布