MST
星途 面试题库

面试题:Python信号量在多线程编程中的中等应用

请使用Python的信号量机制,编写一个多线程程序,实现最多同时有3个线程访问共享资源,并打印出每个线程对共享资源的操作信息,共享资源用一个简单的计数器模拟。
22.0万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
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()