Use cpputils threads that also work fine when fork()-ed
This commit is contained in:
parent
22a3c90d54
commit
52366fb707
27
implementations/caching/cache/PeriodicTask.cpp
vendored
27
implementations/caching/cache/PeriodicTask.cpp
vendored
@ -8,27 +8,24 @@ using namespace cpputils::logging;
|
||||
namespace blockstore {
|
||||
namespace caching {
|
||||
|
||||
PeriodicTask::PeriodicTask(function<void ()> task, double intervalSec) : _thread(), _task(task), _intervalSec(intervalSec) {
|
||||
_thread = boost::thread([this]() {
|
||||
boost::chrono::nanoseconds interval((uint64_t)(UINT64_C(1000000000) * _intervalSec));
|
||||
try {
|
||||
while(true) {
|
||||
boost::this_thread::sleep_for(interval);
|
||||
_task();
|
||||
PeriodicTask::PeriodicTask(function<void ()> task, double intervalSec) :
|
||||
_task(task),
|
||||
_interval((uint64_t)(UINT64_C(1000000000) * intervalSec)),
|
||||
_thread(std::bind(&PeriodicTask::_loopIteration, this)) {
|
||||
_thread.start();
|
||||
}
|
||||
} catch (const boost::thread_interrupted &e) {
|
||||
//Do nothing, exit thread.
|
||||
|
||||
void PeriodicTask::_loopIteration() {
|
||||
try {
|
||||
boost::this_thread::sleep_for(_interval);
|
||||
_task();
|
||||
} catch (const std::exception &e) {
|
||||
LOG(ERROR) << "PeriodicTask crashed: " << e.what();
|
||||
throw;
|
||||
} catch (...) {
|
||||
LOG(ERROR) << "PeriodicTask crashed";
|
||||
throw;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
PeriodicTask::~PeriodicTask() {
|
||||
_thread.interrupt();
|
||||
_thread.join();
|
||||
}
|
||||
|
||||
}
|
||||
|
15
implementations/caching/cache/PeriodicTask.h
vendored
15
implementations/caching/cache/PeriodicTask.h
vendored
@ -3,20 +3,25 @@
|
||||
#define MESSMER_BLOCKSTORE_IMPLEMENTATIONS_CACHING_CACHE_PERIODICTASK_H_
|
||||
|
||||
#include <functional>
|
||||
#include <boost/thread.hpp>
|
||||
#include <messmer/cpp-utils/random/LoopThread.h>
|
||||
#include <boost/chrono.hpp>
|
||||
|
||||
namespace blockstore {
|
||||
namespace caching {
|
||||
|
||||
class PeriodicTask {
|
||||
class PeriodicTask final {
|
||||
public:
|
||||
PeriodicTask(std::function<void ()> task, double intervalSec);
|
||||
virtual ~PeriodicTask();
|
||||
|
||||
private:
|
||||
boost::thread _thread;
|
||||
void _loopIteration();
|
||||
|
||||
std::function<void()> _task;
|
||||
double _intervalSec;
|
||||
boost::chrono::nanoseconds _interval;
|
||||
|
||||
//This member has to be last, so the thread is destructed first. Otherwise the thread might access elements from a
|
||||
//partly destructed PeriodicTask.
|
||||
cpputils::LoopThread _thread;
|
||||
};
|
||||
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user