ログクラスを作る その3
スレッドセーフにする
main.cpp
#include "log.h" #include <thread> int main() { const std::wstring path = L".\\"; const std::wstring name = L"test.txt"; static Log &log = Log::GetInstance(path, name); std::thread t1([&](){ for (int i=0;i<10;i++) log.OutFile(L"Hello thread1!"); }); std::thread t2([&](){ for (int i=0;i<10;i++) log.OutFile(L"Hello thread2!"); }); std::thread t3([&](){ for (int i=0;i<10;i++) log.OutFile(L"Hello thread3!"); }); t1.join(); t2.join(); t3.join(); return 0; }
Log.h
#include <string> #include <mutex> class Log { public: static Log &GetInstance( const std::wstring path, const std::wstring filename ); void OutFile( const std::wstring msg ); private: // コンストラクタデストラクタコピーコンストラクタ代入はプライベートで定義 Log( const std::wstring path, const std::wstring filename ); ~Log() {}; Log(const Log &other) {}; Log& operator=(const Log &other) {}; private: std::recursive_mutex m_mtx; std::wstring m_file_location; };
Log.cpp
#include "Log.h" #include <fstream> Log &Log::GetInstance( const std::wstring path, const std::wstring name ) { static Log instance(path, name); // 一度だけLogインスタンスを生成する return instance; } Log::Log( const std::wstring path, const std::wstring name ) { m_file_location = path; m_file_location += name; } void Log::OutFile( const std::wstring msg ) { std::unique_lock<std::recursive_mutex> lock(m_mtx); std::wofstream wfs; // wstring用filestreamの型 wfs.open(m_file_location, std::ios::app); wfs << msg << std::endl; }