I have the following code which is called by many threads using a thread pool:

Qt Code:
  1. QByteArray PureImageCache::GetImageFromCache(MapType::Types type, Point pos, int zoom)
  2.  
  3. {
  4.  
  5. lock.lockForRead();
  6.  
  7.  
  8. if(gtilecache.isEmpty()|gtilecache.isNull())
  9.  
  10. return ar;
  11.  
  12. QString dir=gtilecache;
  13. Mcounter.lock();
  14. qlonglong id=++ConnCounter;
  15. Mcounter.unlock();
  16.  
  17. QString db=dir+"Data.qmdb";
  18. {
  19.  
  20. cn = QSqlDatabase::addDatabase("QSQLITE",QString::number(id));
  21.  
  22. cn.setDatabaseName(db);
  23. cn.setConnectOptions("QSQLITE_ENABLE_SHARED_CACHE");
  24. if(cn.open())
  25. {
  26. QSqlQuery query(cn);
  27. query.exec(QString("SELECT Tile FROM TilesData WHERE id = (SELECT id FROM Tiles WHERE X=%1 AND Y=%2 AND Zoom=%3 AND Type=%4)").arg(pos.X()).arg(pos.Y()).arg(zoom).arg((int) type));
  28. query.next();
  29. if(query.isValid())
  30. {
  31. ar=query.value(0).toByteArray();
  32. //qDebug()<<"Got";
  33. }else{
  34. //qDebug()<<"Miss";
  35. }
  36. cn.close();
  37. }
  38. }
  39. QSqlDatabase::removeDatabase(QString::number(id));
  40. lock.unlock();
  41. return ar;
  42. }
To copy to clipboard, switch view to plain text mode 
However, I have met one crash (not every time) right after I call the:

Qt Code:
  1. cn = QSqlDatabase::addDatabase(“QSQLITE”,QString::number(id));
To copy to clipboard, switch view to plain text mode 

function. And the call stack says the error is:

Qt Code:
  1. Debug Assertion Failed!
  2. File:f:\dd\vctools\crt_bld\self_x86\crt\src\dbgdel.cpp
  3. Line: 52
  4. Expression:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
To copy to clipboard, switch view to plain text mode 

The cause is within the = operator, it call an atomic assign where inside that atomic assign, there's a delete function cause the crash.
I noticed that there's a shared_null pointer inside the default constructor of QSqlDatabase.
Here is the thing:
The default constructor of QSqlDatabase used a shared_null.
Note that the shared_null is an object indicating an invalid database, not a plain null pointer.

Here is the code: http://code.woboq.org/qt5/qtbase/src...1shared_nullEv
Could it be that the delete is called on to delete the shared_null which is essentially some static variable and caused the crash?
How could I avoid this and continue using QSqlDataBase safely in multi-thread senario?