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

Semaphore()与Condition():Python中线程通信的两个重要工具

发布时间:2024-01-11 13:48:14

Semaphore()和Condition()都是Python中线程通信的重要工具。下面分别介绍它们的使用方法,并给出相应的例子。

1. Semaphore():

Semaphore(信号量)是一种用于控制访问共享资源的方法。在多线程环境下,当一个线程要访问共享资源时,它需要先获取信号量,如果信号量的计数器大于0,则线程可以访问资源,并将计数器减1;如果计数器为0,则线程需要等待,直到有其他线程释放信号量为止。

Semaphore使用示例:

import threading

def worker(semaphore, id):
    semaphore.acquire()
    print(f"Worker {id} is working")
    # 模拟工作耗时
    for _ in range(10000000):
        pass
    print(f"Worker {id} finished working")
    semaphore.release()

# 创建Semaphore对象, 初始值为3
semaphore = threading.Semaphore(3)

# 创建5个线程
threads= []
for i in range(5):
    t = threading.Thread(target=worker, args=(semaphore, i))
    threads.append(t)
    t.start()

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

上述例子中,有5个线程要执行任务,但是由于Semaphore的初始值是3,

所以前3个线程可以直接开始执行,而后面的2个线程需要等待前面3个线程中的一个完成后才能开始执行。

2. Condition():

Condition(条件变量)是一种线程通信的机制,用于一个或多个线程等待另一个线程满足特定的条件后才能继续执行。它通常与锁(Lock)一起使用,通过acquire()和release()控制对共享资源的访问。

Condition使用示例:

import threading

def consumer(condition):
    with condition:
        condition.wait()
        print("Consumer receives the signal and starts consuming")

def producer(condition):
    with condition:
        print("Producer starts producing")
        # 模拟生产过程
        for _ in range(5):
            pass
        print("Producer finishes producing")
        condition.notifyAll()

# 创建Condition对象
condition = threading.Condition()

# 创建一个消费者线程和一个生产者线程
consumer_thread = threading.Thread(target=consumer, args=(condition,))
producer_thread = threading.Thread(target=producer, args=(condition,))

# 启动线程
consumer_thread.start()
producer_thread.start()

# 等待线程完成
consumer_thread.join()
producer_thread.join()

上述例子中,生产者线程首先开始执行,生产完毕后通知消费者线程,消费者线程在接收到通知后开始消费。