#include <fstream> #include <iostream> #include <time.h> #include <string> #include <sstream> struct internal_threadsafe_log_stream { internal_threadsafe_log_stream( const char * strFileName) : m_out( strFileName) {} void threadsafe_write_str( const std::string & str) { m_cs.lock(); m_out << str; m_out.flush(); m_cs.unlock(); } private: std::ofstream m_out; critical_section m_cs; }; struct log_stream { log_stream( internal_threadsafe_log_stream & underlyingStream) : m_underlyingStream( underlyingStream) {} log_stream( const log_stream & from) : m_underlyingStream( from.m_underlyingStream) {} template< class type> log_stream & operator<<( type val) { m_buffer << val; return *this; } void flush() { m_underlyingStream.threadsafe_write_str( m_buffer.str() ); } private: internal_threadsafe_log_stream & m_underlyingStream; std::ostringstream m_buffer; }; log_stream get_log() { static internal_threadsafe_log_stream log( "log.txt"); return log; } // each thread writes 1000 messages void execute_on_each_thread( int idxThread) { for( int idx = 0; idx < 1000; ++idx) { log_stream log = get_log(); log << "message " << idx + 1 << " from thread " << idxThread << "\n"; log.flush(); } } |