import threading
# 创建一个信号量对象,初始值为3,表示最多允许3个线程同时访问
semaphore = threading.Semaphore(3)
def thread_function(thread_id):
print(f"Thread {thread_id} is waiting to acquire the semaphore.")
# 获取信号量
semaphore.acquire()
print(f"Thread {thread_id} has acquired the semaphore.")
# 模拟一些工作
for i in range(5):
print(f"Thread {thread_id} is working: {i}")
# 释放信号量
semaphore.release()
print(f"Thread {thread_id} has released the semaphore.")
# 创建多个线程
threads = []
for i in range(5):
thread = threading.Thread(target=thread_function, args=(i,))
threads.append(thread)
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
print("All threads have finished.")
创建信号量对象:semaphore = threading.Semaphore(3)
创建了一个信号量对象,初始值为3,表示最多允许3个线程同时访问受保护的资源。
获取信号量:semaphore.acquire()
用于获取信号量。如果当前已经有3个线程持有信号量,则其他线程会阻塞,直到有线程释放信号量。
释放信号量:semaphore.release()
用于释放信号量,使得其他等待的线程可以继续获取信号量并执行。
线程函数:thread_function
是每个线程要执行的任务,它首先尝试获取信号量,然后模拟一些工作,最后释放信号量。
创建和启动线程:通过 threading.Thread
创建多个线程,并启动它们。每个线程都会执行 thread_function
函数。
等待线程完成:使用 thread.join()
确保主线程等待所有子线程完成后再继续执行。
这个示例展示了如何使用 Python 的 threading.Semaphore
来控制并发线程的数量,确保不会超过指定数量的线程同时访问共享资源。
上一篇:python tkinter详解
下一篇:rabbitmq python
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站