C++semaphore
时间: 2025-01-11 17:49:21 浏览: 64
### C++ 中信号量的用法
#### 使用 `std::counting_semaphore` 和 `std::binary_semaphore`
自 C++20 起,标准库引入了两种类型的信号量:计数信号量 (`std::counting_semaphore`) 和二进制信号量 (`std::binary_semaphore`)。
#### 计数信号量示例
计数信号量允许指定数量的任务访问共享资源。下面是一个简单的例子:
```cpp
#include <iostream>
#include <thread>
#include <semaphore>
#include <vector>
void worker(std::counting_semaphore<>& sem) {
std::cout << "Waiting for semaphore..." << std::endl;
sem.acquire(); // 获取许可
std::cout << "Semaphore acquired!" << std::endl;
// 执行一些工作...
}
int main() {
const int num_threads = 5;
std::counting_semaphore<> sem(num_threads); // 初始化为num_threads个许可
std::vector<std::jthread> threads;
for (int i = 0; i < num_threads; ++i) {
threads.emplace_back(worker, std::ref(sem));
}
// 发布所有线程所需的许可
for (auto& t : threads) {
sem.release();
}
}
```
此程序创建多个线程并让它们等待获取信号量[^1]。
#### 二进制信号量示例
当只需要控制互斥访问时可以使用二进制信号量。它只持有两个状态之一——可用或不可用。
```cpp
#include <iostream>
#include <thread>
#include <semaphore>
#include <mutex>
class BinaryResource {
public:
void access_resource() {
binary_sem.acquire();
// Critical section begins here.
std::lock_guard<std::mutex> lock(mtx);
static int count = 0;
++count;
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Simulate work being done with resource
--count;
// Critical section ends here.
binary_sem.release();
}
private:
mutable std::binary_semaphore binary_sem{1}; // Initialize to one permit available
mutable std::mutex mtx;
};
// Usage of BinaryResource class omitted for brevity
```
这段代码展示了如何通过二进制信号量来保护临界区[^2]。
阅读全文
相关推荐
















