#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <functional>
class Debouncer {
public:
Debouncer(std::function<void()> callback, std::chrono::milliseconds debounceInterval)
: callback_(callback), debounceInterval_(debounceInterval), isRunning_(false), isCancelled_(false) {}
void Trigger() {
if (isRunning_) {
// 如果防抖操作正在运行,则重置定时器
isCancelled_ = true;
} else {
isRunning_ = true;
isCancelled_ = false;
// 使用异步任务模拟防抖逻辑
std::thread([this]() {
std::this_thread::sleep_for(debounceInterval_);
if (!isCancelled_) {
// 执行回调函数
callback_();
}
isRunning_ = false;
}).detach();
}
}
void Cancel() {
isCancelled_ = true;
}
private:
std::function<void()> callback_;
std::chrono::milliseconds debounceInterval_;
std::atomic<bool> isRunning_;
std::atomic<bool> isCancelled_;
};
// 模拟硬件设备状态改变的函数
void simulateHardwareStateChange(Debouncer& debouncer) {
for (int i = 0; i < 10; ++i) {
std::cout << "Hardware state changed!" << std::endl;
debouncer.Trigger();
std::this_thread::sleep_for(std::chrono::milliseconds(200)); // 模拟状态快速变化
}
}
// 防抖回调函数,这里仅打印一条消息
void debouncedAction() {
std::cout << "Debounced action executed!" << std::endl;
}
int main() {
// 创建一个防抖对象,设置防抖间隔为500毫秒
Debouncer debouncer(debouncedAction, std::chrono::milliseconds(500));
// 模拟硬件设备状态改变
simulateHardwareStateChange(debouncer);
// 等待一段时间以确保所有操作完成
std::this_thread::sleep_for(std::chrono::seconds(2));
return 0;
}
最终效果: