diff --git a/src/SimpleLog.cxx b/src/SimpleLog.cxx index 15e5fc4..f0afd95 100644 --- a/src/SimpleLog.cxx +++ b/src/SimpleLog.cxx @@ -21,6 +21,7 @@ #include #include #include +#include class SimpleLog::Impl { @@ -60,6 +61,7 @@ class SimpleLog::Impl void rotate(); // this renames older files friend class SimpleLog; + std::mutex fileMutex; }; SimpleLog::Impl::Impl() @@ -140,6 +142,9 @@ int SimpleLog::Impl::logV(SimpleLog::Impl::Severity s, const char* message, va_l ix++; buffer[ix] = 0; + int nBytes = 0; // count bytes output + { + std::lock_guard lock(fileMutex); int fd; if (fp != NULL) { if ((ix + logFileSize > rotateMaxBytes) && (rotateMaxBytes > 0)) { @@ -161,10 +166,11 @@ int SimpleLog::Impl::logV(SimpleLog::Impl::Severity s, const char* message, va_l fd = fdStdout; } } - int nBytes = write(fd, buffer, ix); + nBytes = write(fd, buffer, ix); if ((fp != NULL) && (nBytes > 0)) { logFileSize += nBytes; } + } if (nBytes != (int)ix) { return -1; } diff --git a/test/testSimpleLog.cxx b/test/testSimpleLog.cxx index 74fd1f6..d274290 100644 --- a/test/testSimpleLog.cxx +++ b/test/testSimpleLog.cxx @@ -15,6 +15,14 @@ #include #include +#include +#include + +void logWorker(SimpleLog& log, int threadId, int count) { + for (int i = 0; i < count; ++i) { + log.info("Thread %d - test message %d", threadId, i); + } +} int main() { @@ -25,5 +33,18 @@ int main() theLog.info("test message %d", i); } // sleep(10); + + // test parallel threads + theLog.setLogFile("/tmp/testthread.log", 1000, 10, 0); + const int numThreads = 10; + const int messagesPerThread = 10; + std::vector threads; + for (int t = 0; t < numThreads; ++t) { + threads.emplace_back(logWorker, std::ref(theLog), t, messagesPerThread); + } + for (auto& th : threads) { + th.join(); + } + return 0; }