#include "Logger.hpp" #include // Implementacja Singletona AsyncLogger& AsyncLogger::getInstance() { static AsyncLogger instance; return instance; } // Konstruktor AsyncLogger::AsyncLogger() : running(false) {} // Destruktor AsyncLogger::~AsyncLogger() { stop(); } void AsyncLogger::log(const std::string& message) { std::lock_guard lock(queueMutex); logQueue.push(message); cv.notify_one(); } void AsyncLogger::start() { if (running) return; running = true; loggingThread = std::thread(&AsyncLogger::processQueue, this); } void AsyncLogger::stop() { bool expected = true; // atomic_compare_exchange pomaga uniknąć podwójnego zatrzymania if (running.compare_exchange_strong(expected, false)) { cv.notify_one(); if (loggingThread.joinable()) { loggingThread.join(); } } } void AsyncLogger::processQueue() { while (running || !logQueue.empty()) { std::unique_lock lock(queueMutex); // Czekaj, jeśli kolejka pusta I program nadal działa cv.wait(lock, [this] { return !logQueue.empty() || !running; }); while (!logQueue.empty()) { std::string msg = logQueue.front(); logQueue.pop(); // Odblokowujemy mutex na czas wypisywania (dla wydajności) lock.unlock(); std::cout << msg << std::endl; // Blokujemy z powrotem, aby sprawdzić pętlę while lock.lock(); } } }