libcryfs/random/LoopThread.cpp

51 lines
1.2 KiB
C++
Raw Normal View History

#include "LoopThread.h"
2015-10-17 03:08:56 +02:00
#include "../logging/logging.h"
2015-10-28 15:00:24 +01:00
#include "LoopThreadForkHandler.h"
2015-10-17 03:08:56 +02:00
using namespace cpputils::logging;
2015-10-28 15:00:24 +01:00
using std::function;
namespace cpputils {
2015-10-28 15:00:24 +01:00
LoopThread::LoopThread(function<void()> loopIteration): _thread(), _loopIteration(loopIteration) {
LoopThreadForkHandler::singleton().add(this);
}
LoopThread::~LoopThread() {
2015-10-28 15:00:24 +01:00
LoopThreadForkHandler::singleton().remove(this);
stop();
}
void LoopThread::start() {
_thread = boost::thread(std::bind(&LoopThread::main, this));
}
void LoopThread::stop() {
2015-10-28 15:00:24 +01:00
asyncStop();
waitUntilStopped();
}
void LoopThread::asyncStop() {
_thread.interrupt();
2015-10-28 15:00:24 +01:00
}
void LoopThread::waitUntilStopped() {
_thread.join();
}
void LoopThread::main() {
try {
while(true) {
2015-10-28 15:00:24 +01:00
_loopIteration();
}
} catch (const boost::thread_interrupted &e) {
//Do nothing, exit thread.
} catch (const std::exception &e) {
//TODO Think about logging
2015-10-17 03:08:56 +02:00
LOG(ERROR) << "LoopThread crashed: " << e.what();
} catch (...) {
//TODO Think about logging
2015-10-17 03:08:56 +02:00
LOG(ERROR) << "LoopThread crashed";
}
}
2015-10-28 15:00:24 +01:00
}