Files
cos-cpp-sdk-v5/include/util/semaphore.h
a158 3cf88acc07 BG
2026-04-05 20:22:11 +08:00

44 lines
1003 B
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#pragma once
#include <mutex>
#include <condition_variable>
// C++11信号量实现用于滑动窗口控制
class Semaphore {
public:
explicit Semaphore(unsigned int count = 0) : max_count_(count) {}
bool acquire() {
std::unique_lock<std::mutex> lock(mutex_);
if (count_ < max_count_) {
++count_;
return true;
}
return false;
}
void release() {
std::unique_lock<std::mutex> lock(mutex_);
if (count_ <= 0) {
return;
}
--count_;
condition_.notify_one();
}
void wait() {
std::unique_lock<std::mutex> lock(mutex_);
condition_.wait(lock, [this]() { return count_ < max_count_; });
}
unsigned int get_count() const {
std::unique_lock<std::mutex> lock(mutex_);
return count_;
}
private:
mutable std::mutex mutex_;
std::condition_variable condition_;
unsigned int count_ = 0;
const unsigned int max_count_;
};