changeset 950:387fa69f4eaa

Per-thread debug (avoiding some dubious threading problems)
author Chris Cannam
date Fri, 25 Jul 2014 15:21:41 +0100
parents 6d2ece0fe356
children 4b9fc70a37d5
files base/Debug.cpp
diffstat 1 files changed, 22 insertions(+), 9 deletions(-) [+]
line wrap: on
line diff
--- a/base/Debug.cpp	Thu Jul 17 16:22:54 2014 +0100
+++ b/base/Debug.cpp	Fri Jul 25 15:21:41 2014 +0100
@@ -24,20 +24,23 @@
 #include <QDir>
 #include <QCoreApplication>
 #include <QDateTime>
+#include <QThreadStorage>
 
 #include <cstdio>
 
+static QThreadStorage<QDebug *> debugs;
+static QMutex mutex;
+static QFile *logFile = 0;
+static char *prefix = 0;
+
 QDebug &
 getSVDebug()
 {
-    static QFile *logFile = 0;
-    static QDebug *debug = 0;
-    static QMutex mutex;
-    static char *prefix;
-
     mutex.lock();
 
-    if (!debug) {
+    QDebug *debug = 0;
+
+    if (!prefix) {
         prefix = new char[20];
         sprintf(prefix, "[%lu]", (unsigned long)QCoreApplication::applicationPid());
 	QString pfx = ResourceFinder().getUserResourcePrefix();
@@ -48,24 +51,34 @@
             QDebug(QtDebugMsg) << (const char *)prefix
                                << "Opened debug log file "
                                << logFile->fileName();
-            debug = new QDebug(logFile);
         } else {
             QDebug(QtWarningMsg) << (const char *)prefix
                                  << "Failed to open debug log file "
                                  << logFile->fileName()
                                  << " for writing, using console debug instead";
-            debug = new QDebug(QtDebugMsg);
             delete logFile;
             logFile = 0;
         }
+    }
+
+    if (debugs.hasLocalData()) {
+        debug = debugs.localData();
+    } else {
+        if (logFile) {
+            debug = new QDebug(logFile);
+        } else {
+            debug = new QDebug(QtDebugMsg);
+        }
+        debugs.setLocalData(debug);
         *debug << endl << (const char *)prefix << "Log started at "
                << QDateTime::currentDateTime().toString();
     }
 
+    mutex.unlock();
+
     QDebug &dref = *debug;
     dref << endl << (const char *)prefix;
 
-    mutex.unlock();
     return dref;
 }