Функция log теперь не формирует строку, а упаковывает параметры и код логирования в функтор и добавляет его в очередь, обрабатываемую отдельным потоком.

This commit is contained in:
selim 2014-08-24 23:59:41 +04:00
parent 336e342c14
commit 966e729bf8
4 changed files with 24 additions and 11 deletions

View File

@ -5,6 +5,7 @@
#include <thread> #include <thread>
#include <mutex> #include <mutex>
#include <condition_variable> #include <condition_variable>
#include <functional>
class log_queue class log_queue
{ {
@ -12,7 +13,7 @@ private:
std::thread _worker; std::thread _worker;
std::mutex _mutex; std::mutex _mutex;
std::condition_variable _cond; std::condition_variable _cond;
std::queue<std::string> _queue; std::queue<std::function<void()>> _queue;
private: private:
void worker_func(); void worker_func();
@ -20,7 +21,7 @@ private:
public: public:
log_queue(); log_queue();
~log_queue(); ~log_queue();
void add_log(const std::string& logLine); void add_log(const std::function<void()>& logFunc);
}; };
#endif /* LOG_QUEUE_H */ #endif /* LOG_QUEUE_H */

View File

@ -7,20 +7,32 @@
#include <stdexcept> #include <stdexcept>
#include <iostream> #include <iostream>
#include <atomic> #include <atomic>
#include <functional>
class logger class logger
{ {
private: private:
std::atomic<bool> _enabled;
std::stringstream _logLine; std::stringstream _logLine;
log_queue _queue; log_queue _queue;
public: public:
logger(); logger();
void set_enabled(bool enabled)
{
_enabled = enabled;
}
template<typename... Args> void log(const char* s, const Args&... args) template<typename... Args> void log(const char* s, const Args&... args)
{ {
if(_enabled)
{
_queue.add_log([this, s, &args...] {
_logLine.str(""); _logLine.str("");
log_internal(s, args...); log_internal(s, args...);
});
}
} }
private: private:

View File

@ -16,18 +16,17 @@ void log_queue::worker_func()
{ {
std::unique_lock<std::mutex> lock(_mutex); std::unique_lock<std::mutex> lock(_mutex);
_cond.wait(lock, [this] { return !_queue.empty(); }); _cond.wait(lock, [this] { return !_queue.empty(); });
std::string line = _queue.front(); std::function<void()> func = _queue.front();
_queue.pop(); _queue.pop();
lock.unlock(); lock.unlock();
// actually logging func();
std::cout << line << std::endl;
} }
} }
void log_queue::add_log(const std::string& logLine) void log_queue::add_log(const std::function<void()>& logFunc)
{ {
std::lock_guard<std::mutex> lock(_mutex); std::lock_guard<std::mutex> lock(_mutex);
_queue.push(logLine); _queue.push(logFunc);
_cond.notify_one(); _cond.notify_one();
} }

View File

@ -4,7 +4,7 @@
logger ulog; logger ulog;
logger::logger() logger::logger(): _enabled(true)
{ {
} }
@ -17,6 +17,7 @@ void logger::log_internal(const char *s)
_logLine << *s++; _logLine << *s++;
} }
_queue.add_log(_logLine.str()); // actually logging
std::cout << _logLine.str() << std::endl;
} }