comparison data/fileio/FileSource.cpp @ 833:3cc81dbc31bb

Use thread-local storage for network managers; otherwise we get "Cannot create children for a parent that is in a different thread" from nm.get()
author Chris Cannam
date Fri, 19 Jul 2013 13:47:11 +0100
parents 95d4a59295b7
children fcee7e040ab4
comparison
equal deleted inserted replaced
824:420ade1cb6da 833:3cc81dbc31bb
23 #include <QNetworkAccessManager> 23 #include <QNetworkAccessManager>
24 #include <QNetworkReply> 24 #include <QNetworkReply>
25 #include <QFileInfo> 25 #include <QFileInfo>
26 #include <QDir> 26 #include <QDir>
27 #include <QCoreApplication> 27 #include <QCoreApplication>
28 #include <QThreadStorage>
28 29
29 #include <iostream> 30 #include <iostream>
30 #include <cstdlib> 31 #include <cstdlib>
31 32
32 #include <unistd.h> 33 #include <unistd.h>
65 --urlExtantCountMap[url]; 66 --urlExtantCountMap[url];
66 std::cerr << "FileSource: Now " << urlExtantCountMap[url] << " for this url, " << extantCount << " total" << std::endl; 67 std::cerr << "FileSource: Now " << urlExtantCountMap[url] << " for this url, " << extantCount << " total" << std::endl;
67 } 68 }
68 #endif 69 #endif
69 70
70 static QNetworkAccessManager nm; 71 static QThreadStorage<QNetworkAccessManager *> nms;
71 72
72 FileSource::FileSource(QString fileOrUrl, ProgressReporter *reporter, 73 FileSource::FileSource(QString fileOrUrl, ProgressReporter *reporter,
73 QString preferredContentType) : 74 QString preferredContentType) :
74 m_url(fileOrUrl, QUrl::StrictMode), 75 m_url(fileOrUrl, QUrl::StrictMode),
75 m_localFile(0), 76 m_localFile(0),
258 } 259 }
259 260
260 void 261 void
261 FileSource::init() 262 FileSource::init()
262 { 263 {
264 { // check we have a QNetworkAccessManager
265 QMutexLocker locker(&m_mapMutex);
266 if (!nms.hasLocalData()) {
267 nms.setLocalData(new QNetworkAccessManager());
268 }
269 }
270
263 if (isResource()) { 271 if (isResource()) {
264 #ifdef DEBUG_FILE_SOURCE 272 #ifdef DEBUG_FILE_SOURCE
265 std::cerr << "FileSource::init: Is a resource" << std::endl; 273 std::cerr << "FileSource::init: Is a resource" << std::endl;
266 #endif 274 #endif
267 QString resourceFile = m_url.toString(); 275 QString resourceFile = m_url.toString();
441 req.setRawHeader 449 req.setRawHeader
442 ("Accept", 450 ("Accept",
443 QString("%1, */*").arg(m_preferredContentType).toLatin1()); 451 QString("%1, */*").arg(m_preferredContentType).toLatin1());
444 } 452 }
445 453
446 m_reply = nm.get(req); 454 m_reply = nms.localData()->get(req);
447 455
448 connect(m_reply, SIGNAL(readyRead()), 456 connect(m_reply, SIGNAL(readyRead()),
449 this, SLOT(readyRead())); 457 this, SLOT(readyRead()));
450 connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), 458 connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),
451 this, SLOT(replyFailed(QNetworkReply::NetworkError))); 459 this, SLOT(replyFailed(QNetworkReply::NetworkError)));