Search code examples
c++multithreadingqtthread-safetyqmap

Qt: Questions about QMap thread-safety


I am using Qt5 on Windows 7.
In my current app, I have the following (simplified here):

QMap<int, QString> map;

int _WorkerThread_(int index)  
{  
    QString new_element = "whatever";   
    ...   
    map.insert(index, new_element);  // [Q1]  
    ...   
}   

int _MainThread_()   
{   
    int i;
    ...   
    i = some_value();
    map.remove(i); // [Q2]   
    ...    
}   

I have 2 questions about the above code and related to QMap thread-safety (I didn't find much info about it in the Qt documentation):

1) Is map.insert(..) - see code-line marked [Q1] - safe to be used like it is above, when launching more _WorkerThread_ threads simultaneously?

2) How safe/thread-safe is to remove an element from the QMap - see code-line marked [Q2] - when (somehow) it is guaranteed that the value of i is not among the indexes currently in use by working threads?

[Edit]:
So, you're saying I should use a mutex or what?


Solution

  • QMap is not thread-safe, but reentrant.

    To answer to your edit, you can use Qt provided tools like classes (ex: QMutex) or fundamental functions (ex: QCoreApplication::postEvent())

    For more informations, see Qt explanations here : http://doc.qt.io/qt-4.8/threads-reentrancy.html

    Hope that help !