view src/logger.cpp @ 0:add35537fdbb tip

Initial import
author irh <ian.r.hobson@gmail.com>
date Thu, 25 Aug 2011 11:05:55 +0100
parents
children
line wrap: on
line source
//  Copyright 2011, Ian Hobson.
//
//  This file is part of gpsynth.
//
//  gpsynth is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  gpsynth is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with gpsynth in the file COPYING. 
//  If not, see http://www.gnu.org/licenses/.

#include "logger.hpp"

namespace logger {

Logger::Logger()
: output_stream_(std::cout),
  quit_thread_(false) {
  logging_thread_.reset(new boost::thread(&Logger::WorkerThread, this));
}

Logger::~Logger() {
  quit_thread_ = true;
  queue_condition_.notify_one();
  logging_thread_->join();
}

void Logger::LogMessage(const std::string& message) {
  boost::mutex::scoped_lock lock(queue_mutex_);
  log_queue_.push(message);
  queue_condition_.notify_one();
}

void Logger::WorkerThread() {
  while (!quit_thread_) {
    boost::mutex::scoped_lock lock(queue_mutex_);
    while (log_queue_.empty() && !quit_thread_) {
      queue_condition_.wait(lock);
    }
    while (!log_queue_.empty()) {
      output_stream_ << log_queue_.front();
      log_queue_.pop();
    }
    output_stream_ << std::flush;
    queue_condition_.notify_one();
  }
}
  
void Logger::Flush() {
  // wait for the worker thread to empty the work queue
  boost::mutex::scoped_lock lock(queue_mutex_);
  while (!log_queue_.empty()) {
    queue_condition_.wait(lock);
  }
}
  
} // logger namespace