欢迎访问宙启技术站
智能推送

使用BoundedSemaphore()实现Python中的资源池管理

发布时间:2023-12-17 01:50:35

BoundedSemaphore(有界信号量)是Python标准库中的一个同步原语,用于控制共享资源的访问。它允许多个线程同时访问资源,但限制同时访问的线程数量。当资源池中的资源被耗尽时,新的线程需要等待其他线程释放资源后才能访问。

下面是使用BoundedSemaphore实现资源池管理的一个例子:

import threading
import time

# 创建资源池
resource_pool = []
max_resources = 5
resource_sem = threading.BoundedSemaphore(max_resources)

# 定义资源类
class Resource:
    def __init__(self, id):
        self.id = id
    
    def use_resource(self):
        print(f"Thread {threading.currentThread().getName()} is using resource {self.id}")
        time.sleep(1)
        print(f"Thread {threading.currentThread().getName()} finished using resource {self.id}")

# 定义线程类
class WorkerThread(threading.Thread):
    def __init__(self, id):
        threading.Thread.__init__(self)
        self.id = id
    
    def run(self):
        # 获取资源
        resource_sem.acquire()
        try:
            # 从资源池中获取资源并使用
            resource = resource_pool.pop(0)
            resource.use_resource()
            # 使用完后将资源放回资源池
            resource_pool.append(resource)
        finally:
            # 释放资源
            resource_sem.release()

# 初始化资源池
for i in range(max_resources):
    resource_pool.append(Resource(i))

# 创建多个工作线程
worker_threads = []
num_threads = 10
for i in range(num_threads):
    worker_threads.append(WorkerThread(i))

# 启动工作线程
for thread in worker_threads:
    thread.start()

# 等待工作线程结束
for thread in worker_threads:
    thread.join()

在上面的例子中,我们创建了一个资源池,并使用BoundedSemaphore控制资源的访问。资源池中包含5个资源,以Resource类的实例表示。WorkerThread类是工作线程,每个工作线程需要从资源池中获取一个资源并使用。

在run()方法中,工作线程首先调用resource_sem.acquire()来获取资源。当资源池中有可用资源时,线程获得信号量,否则线程将被阻塞直到有可用资源。然后线程从资源池中取出一个资源,并执行use_resource()方法使用资源。使用完资源后,线程将资源放回资源池,并调用resource_sem.release()释放信号量,其他线程可以继续访问资源。

上述代码中创建了10个工作线程,但由于资源池中只有5个资源,因此每次只有5个工作线程可以同时访问资源。其他线程需要等待资源的释放后才能访问。

使用BoundedSemaphore可以很方便地实现资源池管理,控制并发访问资源的数量,避免资源过度使用和滥用。这在一些需要限制并发访问的场景下非常有用,例如数据库连接池、线程池等。