'''
1. threading 模块中定义 Lock() 锁
2. acquire 加锁 release 释放锁
3. 如果在调用acquire方法时,其他线程已经使用六这个互斥锁,那么此时acquire方法会堵塞,知道这个互斥锁释放后才能再次上锁
4. Lock有 acquire() 和 release()。成对出现, 先释放锁后才能加锁 否则会造成死锁
'''
from threading import Thread,Lock
a = 0
b = 1000000
#创建全局互斥锁
lock = Lock()
def sum1():
for i in range(b):
global a
a += 1
print("第1次:",a)
def sum2():
for i in range(b):
global a
a += 1
print("第2次:",a)
def sum3():
lock.acquire()
for i in range(b):
global a
a += 1
print("第1次:",a)
lock.release()
def sum4():
lock.acquire()
for i in range(b):
global a
a += 1
print("第2次:",a)
lock.release()
if __name__ == '__main__':
# 没有加互斥锁
# t1 = Thread(target=sum1)
# t2 = Thread(target=sum2)
'''
第1次: 1348006
第2次: 1522249
'''
# 加 互斥锁
t1 = Thread(target=sum3)
t2 = Thread(target=sum4)
'''
第1次: 1000000
第2次: 2000000
'''
t1.start()
t2.start()
{/tabs-pane}
{tabs-pane label="阻塞主线程,实现同步"}
from threading import Thread
a = 0
b = 1000000
def sum1():
for i in range(b):
global a
a += 1
print("第1次:",a)
def sum2():
for i in range(b):
global a
a += 1
print("第2次:",a)
if __name__ == '__main__':
# 没有加互斥锁
t1 = Thread(target=sum1)
t2 = Thread(target=sum2)
t1.start()
t1.join() # 阻塞主线程,等待子线程执行完
t2.start()
'''
第1次: 1000000
第2次: 2000000
'''
{/tabs-pane}
评论 (0)