スレッドセーフなログクラスを作成しているのですが、スレッドセーフになっていない気がします。
以下のコードを実行したとき、テキストファイルに書かれるのは30行だと思うのですが、結果はそれより少ない行数になったりします。
どこが間違っているのかわからないでいます。アドバイスいただきたいです。
Log.h
c++
1#include <string> 2#include <mutex> 3 4class Log 5{ 6public: 7 static Log &GetInstance( 8 const std::wstring path, 9 const std::wstring filename 10 ); 11 12 void OutFile( 13 const std::wstring msg 14 ); 15 16private: 17 Log( 18 const std::wstring path, 19 const std::wstring filename 20 ); 21 ~Log() {}; 22 Log(const Log &other) {}; 23 Log& operator=(const Log &other) {}; 24 25private: 26 std::mutex m_mtx; 27 std::wstring m_file_location; 28 29};
Log.cpp
c++
1#include "Log.h" 2#include <fstream> 3 4Log &Log::GetInstance( 5 const std::wstring path, 6 const std::wstring name 7) { 8 static Log instance(path, name); 9 return instance; 10} 11 12Log::Log( 13 const std::wstring path, 14 const std::wstring name 15) { 16 m_file_location = path; 17 m_file_location += name; 18} 19 20void Log::OutFile( 21 const std::wstring msg 22) { 23 std::unique_lock<std::recursive_mutex>(m_mtx); 24 std::wofstream wfs; // wstring用filestreamの型 25 wfs.open(m_file_location, std::ios::app); 26 wfs << msg << std::endl; 27}
main.cpp
c++
1#include "log.h" 2#include <thread> 3 4 5int main() { 6 const std::wstring path = L".\"; 7 const std::wstring name = L"test.txt"; 8 9 static Log &log = Log::GetInstance(path, name); 10 11 std::thread t1([&](){ for (int i=0;i<10;i++) log.OutFile(L"Hello thread1!"); }); 12 std::thread t2([&](){ for (int i=0;i<10;i++) log.OutFile(L"Hello thread2!"); }); 13 std::thread t3([&](){ for (int i=0;i<10;i++) log.OutFile(L"Hello thread3!"); }); 14 15 t1.join(); 16 t2.join(); 17 t3.join(); 18 19 return 0; 20}
よさそうにも見えますが、、
出力も貼っていただけないでしょうか?
回答1件
あなたの回答
tips
プレビュー