import threading
#如果多个线程同时访问同一个资源,就会造成线程得不安全
money = 0
#定义一个函数用于存钱
def addMoney():
global money
for i in range(1000000):
money+=1
print(money)
#线程冲突情况
def conflict():
#有五个线程,这五个线程同时取用同一个资源
for _ in range(5):
t = threading.Thread(target=addMoney)
t.start()
pass
#线程冲突解决方案
#一,线程同步
def threadSync():
for _ in range(5):
t = threading.Thread(target=addMoney)
t.start()
t.join()#将线程加入同步队列中,同步既是多个线程在同步队列中依次执行,串行
#同步会造成线程堵塞
#方案二,给资源加锁
lock = threading.Lock()#互斥锁
def addMoney2():
global money
print('当前线程为',threading.current_thread().name)
# 给公共资源处理过程加锁
# if lock.acquire():
# for i in range(1000000):
# money+=1
# print(money)
# #释放
# lock.release()
with lock:
for i in range(1000000):
money+=1
print(money)
print('线程',threading.current_thread().name)
def threadLock():
for _ in range(5):
t = threading.Thread(target=addMoney2)
t.start()
if __name__ == '__main__':
# conflict()
# threadSync()
threadLock()