面试题答案
一键面试import threading
import time
# 创建信号量,最多允许3个线程同时访问
semaphore = threading.Semaphore(3)
# 共享资源计数器
counter = 0
def worker():
global counter
# 获取信号量
semaphore.acquire()
try:
counter += 1
print(f"{threading.current_thread().name} 操作共享资源,计数器值为: {counter}")
time.sleep(1)
finally:
# 释放信号量
semaphore.release()
# 创建并启动5个线程
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.append(t)
t.start()
# 等待所有线程完成
for t in threads:
t.join()