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

使用Semaphore()实现并发控制的方法介绍

发布时间:2023-12-24 13:21:48

Semaphore(信号量)是一种并发控制机制,它用于限制同时访问某个资源的进程/线程的数量。信号量维护一个内部计数器,该计数器表示可用资源的数量。当一个进程/线程想要访问资源时,它必须首先获取信号量,然后执行它的操作,完成后释放信号量。如果信号量的计数器已经为零,那么进程/线程将被阻塞,直到有可用的资源。

在Python中,我们可以使用Semaphore()类来实现信号量。下面是一个使用Semaphore()实现并发控制的例子:

import threading
import time

# 创建一个信号量,初始值为3,表示最多允许3个线程同时访问资源
semaphore = threading.Semaphore(3)

def access_resource(thread_num):
    print(f"Thread {thread_num} is trying to access the resource.")
    # 获取信号量
    semaphore.acquire()
    print(f"Thread {thread_num} is accessing the resource.")
    time.sleep(2)  # 模拟访问资源需要一定的时间
    print(f"Thread {thread_num} has finished accessing the resource.")
    # 释放信号量
    semaphore.release()

# 创建10个线程同时访问资源
threads = []
for i in range(10):
    thread = threading.Thread(target=access_resource, args=(i,))
    threads.append(thread)
    thread.start()

# 等待所有线程执行完成
for thread in threads:
    thread.join()

在上面的例子中,我们创建了一个初始值为3的信号量对象semaphore,表示最多允许3个线程同时访问资源。然后,我们创建了10个线程来访问资源。每个线程在执行操作之前首先需要获取信号量(semaphore.acquire()),如果当前可用资源的数量已经为零,那么线程将被阻塞在这里。当一个线程获取到信号量后,它将执行自己的操作,并在完成后释放信号量(semaphore.release())。这样,最多同时有3个线程可以访问资源,其他线程需要等待。

运行上述代码,你可以看到输出结果类似于下面的样子:

Thread 0 is trying to access the resource.
Thread 0 is accessing the resource.
Thread 1 is trying to access the resource.
Thread 1 is accessing the resource.
Thread 2 is trying to access the resource.
Thread 2 is accessing the resource.
Thread 3 is trying to access the resource.
Thread 4 is trying to access the resource.
Thread 5 is trying to access the resource.
Thread 6 is trying to access the resource.
Thread 7 is trying to access the resource.
Thread 8 is trying to access the resource.
Thread 5 is accessing the resource.
Thread 3 is accessing the resource.
Thread 9 is trying to access the resource.
Thread 8 is accessing the resource.
Thread 6 is accessing the resource.
Thread 4 is accessing the resource.
Thread 7 is accessing the resource.
Thread 9 is accessing the resource.
Thread 1 has finished accessing the resource.
Thread 2 has finished accessing the resource.
Thread 0 has finished accessing the resource.
Thread 7 has finished accessing the resource.
Thread 8 has finished accessing the resource.
Thread 5 has finished accessing the resource.
Thread 6 has finished accessing the resource.
Thread 3 has finished accessing the resource.
Thread 4 has finished accessing the resource.
Thread 9 has finished accessing the resource.

从输出结果可以看出,最多有3个线程同时访问资源,其他线程需要等待。这样能够保证并发控制,限制了同时访问资源的数量。