【一】未加鎖會產生的問題
- 所有子執行緒都會進行阻塞操作,導致最後的改變只是改了一次
from threading import Thread
import time
money = 100
def task():
global money
# 模擬獲取到車票資訊
temp = money
# 模擬網路延遲
time.sleep(2)
# 模擬購票
money = temp - 1
def main():
task_list = [Thread(target=work) for i in range(100)]
[task.start() for task in task_list]
[task.join() for task in task_list]
# 所有子執行緒結束後列印 money
print(money)
if __name__ == '__main__':
main()
# 99
【二】加鎖後
from threading import Thread, Lock
import time
money = 100
# 生成鎖
mutex = Lock()
def work():
global money
# 資料發生改變之前加鎖
mutex.acquire()
# 模擬獲取到車票資訊
temp = money
# 模擬網路延遲
time.sleep(0.6)
# 模擬購票
money = temp - 1
# 資料發生改變後解鎖
mutex.release()
def main():
task_list = [Thread(target=work) for i in range(100)]
[task.start() for task in task_list]
[task.join() for task in task_list]
# 所有子執行緒結束後列印 money
print(money)
if __name__ == '__main__':
main()
# 0