'''
【线程冲突】示例:
多个线程并发访问同一个变量而互相干扰
互斥锁
状态:锁定/非锁定
#创建锁
lock = threading.Lock()
#锁定
lock.acquire()
#释放
lock.release()
'''
import threading
import time
money = 0
def addMoney():
global money
for i in range(1000000):
money += 1
print(money)
lock = threading.Lock()
def addMoneyWithLock():
time.sleep(1)
global money
with lock:
for i in range(1000000):
money += 1
print(money)
def conflictDemo():
for i in range(5):
t = threading.Thread(target=addMoney)
t.start()
def handleConflictBySync():
for i in range(5):
t = threading.Thread(target=addMoney)
t.start()
t.join()
def handleConflictByLock():
for i in range(5):
t = threading.Thread(target=addMoneyWithLock)
t.start()
if __name__ == '__main__':
handleConflictByLock()
pass