/////////////////////////////////////////////////////////////// // MT1-Q7.cpp - class declaration for logger // // // // Jim Fawcett, CSE687 - Object Oriented Deisgn, Spring 2019 // /////////////////////////////////////////////////////////////// #include #include #include "../Cpp11-BlockingQueue/Cpp11-BlockingQueue.h" //// required solution starts here //////////////////////////// template class Logger { public: Logger(std::ostream& out = std::cout); Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; void log(const T& t); void wait(); private: std::ostream& out_; // streams are not copyable or assignable BlockingQueue msgQ_; // BlockingQueue is not copyable or assignable std::thread thrd_; void threadProc(BlockingQueue& bQueue); }; //// required solution ends here ////////////////////////////// template void Logger::threadProc(BlockingQueue& bQueue) { while (true) { T t = bQueue.deQ(); out_ << "\n " << t; if (t == "quit") break; } } template Logger::Logger(std::ostream& out) : out_(out) { std::thread thrd(&Logger::threadProc, this, std::ref(msgQ_)); thrd_ = std::move(thrd); } template void Logger::wait() { thrd_.join(); } template void Logger::log(const T& t) { msgQ_.enQ(t); } #include int main() { std::cout << "\n MT1-Q7 - Logger Declaration"; std::cout << "\n -----------------------------\n"; Logger logger; for (size_t i = 0; i < 10; ++i) { logger.log("logging msg #" + std::to_string(i + 1)); } logger.log("quit"); std::ofstream fout("fileLogger.txt"); if (fout.good()) { Logger fileLogger(fout); for (size_t i = 0; i < 10; ++i) { fileLogger.log("logging file-msg #" + std::to_string(i + 1)); } fileLogger.log("quit"); fileLogger.wait(); } logger.wait(); std::cout << "\n\n"; }