cpputil/src/log_queue.cpp

41 lines
850 B
C++

#include "log_queue.h"
#include <iostream>
log_queue::log_queue(): _working(true), _worker(&log_queue::worker_func, this)
{
}
log_queue::~log_queue()
{
std::unique_lock<std::mutex> lock(_mutex);
_queue.push([]{});
_working = false;
_cond.notify_one();
lock.unlock();
_worker.join();
}
void log_queue::worker_func()
{
while(true)
{
std::unique_lock<std::mutex> lock(_mutex);
_cond.wait(lock, [this] { return !_queue.empty(); });
std::function<void()> func = _queue.front();
_queue.pop();
if(_queue.empty() && !_working)
return;
lock.unlock();
func();
}
}
void log_queue::add_log(const std::function<void()>& logFunc)
{
std::lock_guard<std::mutex> lock(_mutex);
_queue.push(logFunc);
_cond.notify_one();
}