面试题答案
一键面试import threading
# 共享变量
counter = 0
# 创建锁对象
lock = threading.Lock()
def increment():
global counter
for _ in range(100000):
# 获取锁
lock.acquire()
try:
counter += 1
finally:
# 释放锁
lock.release()
# 创建多个线程
threads = []
for _ in range(5):
t = threading.Thread(target=increment)
threads.append(t)
t.start()
# 等待所有线程完成
for t in threads:
t.join()
print(f"Final counter value: {counter}")