线程锁:当有一个数据有多个线程对其进行修改的时候,任何一个线程改变他都会对其他线程造成影响,如果我们想某一个线程在使用完之前,其他线程不能对其修改,就需要对这个线程加一个线程锁
我们来拿一个程序来说明线程锁的作用如下程序我们将线程锁注销掉,看下输出结果
count = 0
def get_money(money):
global count
count +=money
count +=money
count -=money
# 创建一个线程锁对象
lock =threading.Lock()
def lock_thread(money):
# 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()
# 创建线程的参数为一个元组的类型
# 主线程开辟一个分线程
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')
输出结果为
hello world
当前线程为 thread1
当前线程为 thread2
当前线程为 thread2
当前线程为 thread1
我们可以看到两个线程不是按照有序的排列执行,而是随机的执行,会出现许多不同的结果,而当我们将线程锁代码解注释得到的结果就只有一个
hello world
当前线程为 thread1
当前线程为 thread1
当前线程为 thread2
当前线程为 thread2