[boost][thread] synchronization fails - why?
Hi, I've written a small logging class which I use for debugging in a multithreaded environment. I.e. different concurrent (boost) threads may instantiate an object of class logmsg, which amongst other things writes some message to the console. To synchronize the output I lock a global mutex whenever the logmsg constructor is invoked. Unfortunately it simply doesn't work. I still end up with output from different threads being mixed up almost as if there was no synchronization. I write 'almost' because if I remove the locking it's actually getting worse (crazy, huh). I added the code for allocating the console (it's an MFC project), because I believe it could have something to do with it, since the console itself is running in a separate (non-boost) thread. --- FILE* pConsole; boost::mutex consoleMutex; class logmsg { public: logmsg(const void* source, const char* msg, ...); }; logmsg::logmsg(const void* source, const char* msg, ...) { boost::mutex::scoped_lock lock(consoleMutex); if (!pConsole) create_console(); cout << msg << endl; } void create_console() { AllocConsole(); int hConsole = _open_osfhandle( (long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT ); pConsole = _fdopen(hConsole, "w"); setvbuf(pConsole, NULL, _IONBF, 0); //disables buffering *stdout = *pConsole; } --- Best regards, Alex
As it seems to me - it must work ok. At least this (simplified variant): FILE* pConsole; boost::mutex consoleMutex; class logmsg { public: logmsg(const void* source, const char* msg) { boost::mutex::scoped_lock lock(consoleMutex); cout << msg << endl; } }; Note that: 1) there are no variable params. Probably problem was in that you haven't dealed with them (va_list, va_arg ...) 2) if you are creating logmsg in constructor of some global variable, then consoleMutex can be created later and you will actually work not with mutex, but with garbage in memory
Thanks Roman, I believe I found a solution now - and it's not a boost/thread-issue. The problem seems to be, that the console is mixing things up. If I write to a file instead of the console, output is in order. Still I don't know why, but I don't care either.
participants (2)
-
Alexander Heinrich
-
Roman Shmelev