C++ semaphore
时间: 2025-03-23 20:02:46 浏览: 34
### C++ 中信号量的实现与用法
在现代 C++ 编程中,`std::binary_semaphore` 和 `std::counting_semaphore` 是标准库提供的两种信号量工具。它们分别用于二元信号量和计数信号量的操作。
#### 1. **C++ 标准库中的信号量**
自 C++20 起,引入了两个新的同步原语:`std::binary_semaphore` 和 `std::counting_semaphore`。这些类提供了线程安全的方式来进行资源管理或协调多个线程之间的操作[^4]。
- **`std::binary_semaphore`**: 表示一种只有两种状态(0 或 1)的信号量。它通常用来控制对共享资源的访问。
```cpp
std::binary_semaphore bin_sem(0); // 初始值为 0
void producer() {
// 生产者完成工作后释放信号量
bin_sem.release();
}
void consumer() {
// 消费者等待生产者的信号
bin_sem.acquire();
}
```
- **`std::counting_semaphore`**: 提供了一个可配置的最大计数值,允许更灵活的多线程协作场景。
```cpp
std::counting_semaphore<5> cnt_sem(3); // 最大值为 5,初始值为 3
void thread_func() {
cnt_sem.acquire(); // 减少计数器直到达到最大限制
// 执行临界区代码...
cnt_sem.release(); // 增加计数器
}
```
以上代码展示了如何通过信号量来保护共享资源并确保线程间的正确顺序执行[^4]。
#### 2. **手动实现信号量**
如果目标平台不支持 C++20 的新特性,则可以基于互斥锁 (`mutex`) 和条件变量 (`condition_variable`) 来模拟信号量的行为:
```cpp
#include <mutex>
#include <condition_variable>
class Semaphore {
private:
unsigned int count;
mutable std::mutex mtx;
std::condition_variable cv;
public:
explicit Semaphore(unsigned int initial_count = 0) : count(initial_count) {}
void acquire() const {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this]() { return count > 0; });
--count;
}
void release() const {
std::lock_guard<std::mutex> lock(mtx);
++count;
cv.notify_one();
}
};
```
上述实现定义了一个简单的计数信号量类 `Semaphore`,其中包含了基本的功能——获取许可 (`acquire`) 和释放许可 (`release`)。这种设计能够满足大多数并发编程的需求[^5]。
#### 3. **实际应用案例**
假设有一个服务器程序需要处理来自客户端的消息队列,并且希望主线程仅当消息可用时才继续运行。此时可以通过信号量机制通知主线程何时可以从队列读取消息[^6]:
```cpp
// 使用 counting_semaphore 控制消息数量
std::counting_semaphore<10> msg_available(0);
void handle_message(const Message& message) {
process(message);
}
void worker_thread(Queue<Message>& queue) {
while (true) {
auto message = queue.pop();
msg_available.release(); // 发送信号表示有新消息到达
handle_message(message);
}
}
```
在此例子中,每当一条新消息被加入到队列时都会调用一次 `msg_available.release()` 方法;而消费者则会阻塞于 `msg_available.acquire()` 直至收到足够的信号为止[^7]。
---
阅读全文
相关推荐
















