Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // compile with
- // g++ -o log_example main.cpp -pthread -std=c++11 -O4
- //
- #include <string>
- #include <iostream>
- #include <iomanip>
- #include <sstream>
- #include <fstream>
- #include <vector>
- #include <memory>
- #include <future>
- #include <thread>
- #include <mutex>
- #include <sys/time.h>
- //{ unicode wrappers
- typedef wchar_t tchar;
- typedef wchar_t ttimestr[40];
- typedef std::wstring tstring;
- typedef std::wostream tostream;
- typedef std::wostringstream tostringstream;
- typedef std::wofstream tofstream;
- inline static size_t tcstime( tchar* str, size_t count, tchar const* fmt, tm* time ) {
- return wcsftime( str, count, fmt, time );
- }
- //}
- ///////////////////////////////////////////////////////////////////////////////
- template <typename T, size_t N> inline size_t _countof(T (&)[N]) { return N; }
- ///////////////////////////////////////////////////////////////////////////////
- class LogMessage {
- friend tostream& operator<< ( tostream& os, LogMessage const& lm );
- private:
- tstring msg;
- struct timeval time;
- public:
- LogMessage( tstring const& str )
- : msg( str ), time()
- {
- gettimeofday( &time, NULL );
- }
- virtual~ LogMessage() {
- }
- };
- ///////////////////////////////////////////////////////////////////////////////
- inline tostream& operator<< ( tostream& os, LogMessage const& lm ) {
- struct tm timeSt = { 0 };
- ttimestr timeBuffer = { 0 };
- if ( tcstime( timeBuffer, _countof(timeBuffer), L"%d.%m.%y %T", localtime_r( &lm.time.tv_sec, &timeSt )))
- os << timeBuffer << L":" << std::setfill(L'0') << std::setw(6) << lm.time.tv_usec;
- else
- os << L"time not recognized";
- os << L"\t" << lm.msg << std::endl;
- os.flush();
- return os;
- }
- ///////////////////////////////////////////////////////////////////////////////
- class MessagesQueue {
- private:
- typedef std::shared_ptr<LogMessage> MsgObject;
- typedef std::vector<MsgObject> MsgList;
- private:
- tostream& output;
- std::mutex collector_mutex, printer_mutex, start_mutex;
- MsgList * messagesCollector, * messagesPrinter;
- private:
- void start()
- {
- if ( printer_mutex.try_lock())
- {
- bool nothingToPrint = messagesPrinter->empty();
- printer_mutex.unlock();
- if ( nothingToPrint )
- {
- bool collectedToPrint = false;
- if ( collector_mutex.try_lock())
- {
- collectedToPrint = !messagesCollector->empty();
- collector_mutex.unlock();
- }
- if ( collectedToPrint )
- {
- {
- std::unique_lock<std::mutex> pl(printer_mutex, std::defer_lock);
- std::unique_lock<std::mutex> cl(collector_mutex, std::defer_lock);
- std::lock( pl, cl );
- std::swap( messagesPrinter, messagesCollector );
- }
- std::async( std::launch::async, [&]() {
- printer_mutex.lock();
- for ( MsgObject& m: *messagesPrinter) {
- output << *(m.get());
- }
- messagesPrinter->clear();
- printer_mutex.unlock();
- });
- }
- }
- }
- }
- public:
- MessagesQueue(tostream &os)
- : output(os),
- messagesCollector( new MsgList()),
- messagesPrinter( new MsgList())
- {
- }
- virtual ~MessagesQueue() {
- std::unique_lock<std::mutex> pl(printer_mutex, std::defer_lock);
- std::unique_lock<std::mutex> cl(collector_mutex, std::defer_lock);
- std::unique_lock<std::mutex> sl(start_mutex, std::defer_lock);
- std::lock( pl, cl, sl );
- delete messagesCollector;
- delete messagesPrinter;
- }
- void Message( tstring const& a ) {
- {
- collector_mutex.lock();
- MsgObject o (new LogMessage( a ));
- messagesCollector->push_back( o );
- collector_mutex.unlock();
- }
- if (start_mutex.try_lock()) {
- start();
- start_mutex.unlock();
- }
- }
- };
- ///////////////////////////////////////////////////////////////////////////////
- class Widget {
- private:
- tstring const widget_id;
- public:
- Widget( tstring const& id ) : widget_id( id ) {}
- Widget( Widget const& w ) : widget_id( w.widget_id ) {}
- const tstring &get_widget_id() const {
- return widget_id;
- }
- };
- ///////////////////////////////////////////////////////////////////////////////
- typedef std::vector<Widget> WList;
- ///////////////////////////////////////////////////////////////////////////////
- void f ( bool &stop, WList wl, MessagesQueue& log ) {
- while (!stop) {
- bool firstNoComma = true;
- tostringstream os;
- os << L"The system detected a Foo event while being in state Bar and keeping track of the folowing Widgets: [";
- for ( auto const& i: wl) {
- if ( stop ) {
- break;
- }
- if (!firstNoComma) {
- os << L", ";
- } else {
- firstNoComma = false;
- }
- os << i.get_widget_id();
- }
- os << L"]";
- log.Message( os.str());
- }
- }
- ///////////////////////////////////////////////////////////////////////////////
- ///////////////////////////////////////////////////////////////////////////////
- int main(int argc, char** argv) {
- tofstream outfile( "output.log", std::ios::out|std::ios::ate );
- MessagesQueue log( outfile );
- bool threads_stop = false;
- Widget th1[] = {
- Widget( L"Widget1" ),
- Widget( L"Widget2" ),
- Widget( L"Widget3" )
- };
- Widget th2[] = {
- Widget( L"Widget4" ),
- Widget( L"Widget5" ),
- Widget( L"Widget6" )
- };
- Widget th3[] = {
- Widget( L"Widget7" ),
- Widget( L"Widget8" ),
- Widget( L"Widget9" )
- };
- WList
- thlist1( th1, th1 + _countof(th1)),
- thlist2( th2, th2 + _countof(th2)),
- thlist3( th3, th3 + _countof(th3));
- std::thread t1 ( f, std::ref(threads_stop), thlist1, std::ref(log));
- std::thread t2 ( f, std::ref(threads_stop), thlist2, std::ref(log));
- std::thread t3 ( f, std::ref(threads_stop), thlist3, std::ref(log));
- {
- std::async( std::launch::async, [&]() {
- std::chrono::seconds dura( 20 );
- std::this_thread::sleep_for( dura );
- threads_stop = true;
- });
- }
- t1.join();
- t2.join();
- t3.join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment