我在我的C++应用程序中找到了以下回调定时器的实现方式。但是,这种实现方式要求我从“start”调用者中“join”线程,这实际上会阻塞start函数的调用者。
我真正想做的是:
1. 某人可以多次调用foo(data)并将它们存储在数据库中。 2. 每当调用foo(data)时,它都会启动一个几秒钟的定时器。 3. 当计时器在倒数时,foo(data)可以被多次调用并存储多个项,但直到计时器结束才调用erase。 4. 计时器到期后,一次性调用“remove”函数以从数据库中删除所有记录。
基本上,我想能够执行任务,等待几秒钟后批量执行单个批量任务B。
我真正想做的是:
1. 某人可以多次调用foo(data)并将它们存储在数据库中。 2. 每当调用foo(data)时,它都会启动一个几秒钟的定时器。 3. 当计时器在倒数时,foo(data)可以被多次调用并存储多个项,但直到计时器结束才调用erase。 4. 计时器到期后,一次性调用“remove”函数以从数据库中删除所有记录。
基本上,我想能够执行任务,等待几秒钟后批量执行单个批量任务B。
class CallBackTimer {
public:
/**
* Constructor of the CallBackTimer
*/
CallBackTimer() :_execute(false) { }
/**
* Destructor
*/
~CallBackTimer() {
if (_execute.load(std::memory_order_acquire)) {
stop();
};
}
/**
* Stops the timer
*/
void stop() {
_execute.store(false, std::memory_order_release);
if (_thd.joinable()) {
_thd.join();
}
}
/**
* Start the timer function
* @param interval Repeating duration in milliseconds, 0 indicates the @func will run only once
* @param delay Time in milliseconds to wait before the first callback
* @param func Callback function
*/
void start(int interval, int delay, std::function<void(void)> func) {
if(_execute.load(std::memory_order_acquire)) {
stop();
};
_execute.store(true, std::memory_order_release);
_thd = std::thread([this, interval, delay, func]() {
std::this_thread::sleep_for(std::chrono::milliseconds(delay));
if (interval == 0) {
func();
stop();
} else {
while (_execute.load(std::memory_order_acquire)) {
func();
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
}
}
});
}
/**
* Check if the timer is currently running
* @return bool, true if timer is running, false otherwise.
*/
bool is_running() const noexcept {
return ( _execute.load(std::memory_order_acquire) && _thd.joinable() );
}
private:
std::atomic<bool> _execute;
std::thread _thd;
};
我尝试使用thread.detach()修改上述代码。然而,我遇到了一个问题,即分离的线程无法从数据库中写入(擦除)。
非常感谢您的帮助和建议!