std::counting_semaphore
什么是 std::counting_semaphore
std::counting_semaphore 是 C++20 引入的轻量级同步原语,定义在 <semaphore> 头文件中。它维护一个内部计数器,acquire() 会递减计数器(计数器为零时阻塞),release() 会递增计数器(并唤醒阻塞的线程)。
与 std::mutex 不同,信号量不绑定到特定线程——一个线程可以 acquire,另一个线程可以 release。这让信号量适合实现生产者-消费者模式、限流、线程间信号通知等场景。
#include <semaphore>
// 模板参数是计数器的最小最大值(编译期常量)
// 构造参数是计数器的初始值
std::counting_semaphore<10> sem(3); // 最大至少10,初始值3counting_semaphore 的成员函数
| 函数 | 说明 |
|---|---|
counting_semaphore(n) | 构造,初始计数器为 n |
release(n=1) | 计数器加 n,唤醒等待线程 |
acquire() | 计数器减 1(为零时阻塞) |
try_acquire() | 尝试减 1,不阻塞,返回 bool |
try_acquire_for(duration) | 限时尝试获取 |
try_acquire_until(time_point) | 等到指定时间点尝试获取 |
max() | 静态函数,返回计数器支持的最大值 |
基本示例
#include <iostream>
#include <thread>
#include <semaphore>
#include <vector>
#include <mutex>
#include <string>
#include <chrono>
#include <queue>
std::mutex cout_mutex;
void safe_print(const std::string& msg) {
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << msg << std::endl;
}
// ============================
// 示例1:限制并发数量
// ============================
void concurrency_limit_demo() {
// 最多允许 3 个线程同时工作
std::counting_semaphore<10> sem(3);
std::vector<std::jthread> threads;
for (int i = 0; i < 8; i++) {
threads.emplace_back([&sem, i] {
safe_print(" 线程 " + std::to_string(i) + " 等待获取信号量...");
sem.acquire(); // 获取许可(计数器减1)
safe_print(" 线程 " + std::to_string(i) + " 开始工作");
// 模拟工作
std::this_thread::sleep_for(std::chrono::milliseconds(100));
safe_print(" 线程 " + std::to_string(i) + " 完成");
sem.release(); // 释放许可(计数器加1)
});
}
}
// ============================
// 示例2:生产者-消费者信号通知
// ============================
void producer_consumer_demo() {
std::queue<int> buffer;
std::mutex buffer_mutex;
// items 表示缓冲区中有多少数据可消费(初始为0)
// spaces 表示缓冲区还有多少空位(初始为5)
std::counting_semaphore<10> items(0);
std::counting_semaphore<10> spaces(5);
// 生产者
std::jthread producer([&](std::stop_token stoken) {
for (int i = 1; i <= 10 && !stoken.stop_requested(); i++) {
spaces.acquire(); // 等待空位
{
std::lock_guard lock(buffer_mutex);
buffer.push(i);
safe_print(" 生产: " + std::to_string(i)
+ " (缓冲区大小: " + std::to_string(buffer.size()) + ")");
}
items.release(); // 通知有新数据
std::this_thread::sleep_for(std::chrono::milliseconds(30));
}
});
// 消费者
std::jthread consumer([&](std::stop_token stoken) {
for (int i = 0; i < 10 && !stoken.stop_requested(); i++) {
items.acquire(); // 等待数据
int value;
{
std::lock_guard lock(buffer_mutex);
value = buffer.front();
buffer.pop();
}
spaces.release(); // 通知有空位
safe_print(" 消费: " + std::to_string(value));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
});
}
// ============================
// 示例3:线程间信号通知(一次性)
// ============================
void signal_demo() {
// 初始值为0:消费者必须等待生产者发信号
std::counting_semaphore<1> ready(0);
std::string shared_data;
std::jthread producer([&] {
// 准备数据
std::this_thread::sleep_for(std::chrono::milliseconds(100));
shared_data = "数据已准备好";
safe_print(" 生产者: 数据准备完毕");
ready.release(); // 通知消费者
});
std::jthread consumer([&] {
safe_print(" 消费者: 等待数据...");
ready.acquire(); // 等待通知
safe_print(" 消费者: 收到 -> " + shared_data);
});
}
// ============================
// 示例4:try_acquire 非阻塞尝试
// ============================
void try_acquire_demo() {
std::counting_semaphore<5> sem(2);
// 获取两次,计数器变为0
bool r1 = sem.try_acquire(); // true,计数器: 2->1
bool r2 = sem.try_acquire(); // true,计数器: 1->0
bool r3 = sem.try_acquire(); // false,计数器已经是0
std::cout << std::boolalpha;
std::cout << "r1: " << r1 << std::endl; // true
std::cout << "r2: " << r2 << std::endl; // true
std::cout << "r3: " << r3 << std::endl; // false
// 释放后再试
sem.release();
bool r4 = sem.try_acquire(); // true
std::cout << "r4: " << r4 << std::endl; // true
}
// ============================
// 示例5:try_acquire_for 限时等待
// ============================
void timed_acquire_demo() {
std::counting_semaphore<5> sem(0);
std::jthread releaser([&] {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
safe_print(" 释放信号量");
sem.release();
});
safe_print(" 尝试限时获取(100ms)...");
bool got_it = sem.try_acquire_for(std::chrono::milliseconds(100));
safe_print(" 100ms 结果: " + std::string(got_it ? "成功" : "超时"));
safe_print(" 尝试限时获取(200ms)...");
got_it = sem.try_acquire_for(std::chrono::milliseconds(200));
safe_print(" 200ms 结果: " + std::string(got_it ? "成功" : "超时"));
}
// ============================
// 示例6:release 多次
// ============================
void multi_release_demo() {
std::counting_semaphore<10> sem(0);
// 一次释放多个许可
sem.release(3); // 计数器从0变为3
bool r1 = sem.try_acquire(); // true
bool r2 = sem.try_acquire(); // true
bool r3 = sem.try_acquire(); // true
bool r4 = sem.try_acquire(); // false
std::cout << std::boolalpha;
std::cout << "连续获取: " << r1 << " " << r2 << " " << r3 << " " << r4 << std::endl;
}
// ============================
// 示例7:连接池模拟
// ============================
void connection_pool_demo() {
constexpr int pool_size = 3;
// 信号量控制可用连接数
std::counting_semaphore<10> available(pool_size);
std::mutex pool_mutex;
int active_connections = 0;
std::vector<std::jthread> clients;
for (int i = 0; i < 6; i++) {
clients.emplace_back([&, i] {
available.acquire(); // 获取连接
{
std::lock_guard lock(pool_mutex);
active_connections++;
safe_print(" 客户端 " + std::to_string(i) + " 获取连接 (活跃: "
+ std::to_string(active_connections) + ")");
}
// 使用连接
std::this_thread::sleep_for(std::chrono::milliseconds(80));
{
std::lock_guard lock(pool_mutex);
active_connections--;
safe_print(" 客户端 " + std::to_string(i) + " 归还连接 (活跃: "
+ std::to_string(active_connections) + ")");
}
available.release(); // 归还连接
});
}
}
int main() {
std::cout << "=== 限制并发 ===" << std::endl;
concurrency_limit_demo();
std::cout << "\n=== 生产者-消费者 ===" << std::endl;
producer_consumer_demo();
std::cout << "\n=== 信号通知 ===" << std::endl;
signal_demo();
std::cout << "\n=== try_acquire ===" << std::endl;
try_acquire_demo();
std::cout << "\n=== 限时等待 ===" << std::endl;
timed_acquire_demo();
std::cout << "\n=== 多次释放 ===" << std::endl;
multi_release_demo();
std::cout << "\n=== 连接池 ===" << std::endl;
connection_pool_demo();
return 0;
}counting_semaphore vs mutex
| 特性 | counting_semaphore | mutex |
|---|---|---|
| 绑定线程 | 不绑定 | 绑定(谁锁谁解) |
| 并发数 | 可以大于1 | 只能1 |
| 用途 | 限流、信号通知 | 互斥访问 |
| 超时获取 | 支持 | try_lock_for(timed_mutex) |
| 跨线程释放 | 可以 | 不可以(未定义行为) |
适用场景
- 限制同时访问资源的线程数(连接池、线程池)
- 生产者-消费者的信号通知
- 跨线程的事件通知(acquire 和 release 在不同线程)
- 替代条件变量的简单等待/通知
- 实现限流器
常见问题
counting_semaphore 的模板参数是什么意思?
模板参数 LeastMaxValue 是计数器保证支持的最小最大值。实际最大值可能更大(通过 max() 查询)。这个参数让实现可以根据需要优化存储。
release 的参数可以大于 LeastMaxValue 吗?
release 之后的计数器值不能超过 max()。如果超过,行为未定义。
信号量初始值可以是0吗?
可以。初始值为0意味着第一个 acquire 调用会阻塞,直到有其他线程调用 release。这正是信号通知模式的用法。
信号量是线程安全的吗?
是的。所有操作(acquire、release、try_acquire 等)都是线程安全的。
注意事项
- release 后计数器不能超过 max()
- 信号量不绑定线程——与 mutex 的重要区别
- 析构信号量时不能有线程在 acquire 等待
- try_acquire 不阻塞,适合轮询场景
- 信号量不能复制或移动
- 需要
<semaphore>头文件
总结
std::counting_semaphore 是 C++20 引入的轻量级同步原语,通过内部计数器控制并发访问。acquire 递减计数器(为零时阻塞),release 递增计数器(唤醒等待线程)。与 mutex 最大的区别是信号量不绑定线程——可以在一个线程 acquire,在另一个线程 release,适合生产者-消费者等跨线程信号通知场景。counting_semaphore 还支持限制并发数量,比如连接池、限流器等需要控制同时访问数的场景。