Qt: Questions about QMap thread-safety
Asked Answered
L

1

6

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?

Larcher answered 29/6, 2016 at 12:12 Comment(5)
QMap is "reentrant" defined here: doc.qt.io/qt-4.8/threads-reentrancy.html#reentrant . My conclusion is NOT thread safe. ie 1) No, 2) No.Berkeleian
Not thread safe, insertions and removal modify the container, regardless of the specific index you are working on.Hahnke
Yes, the simplest solution is to guard access to the map with a mutex.Sarcomatosis
@PavelStrakhov : And a complex one...? Even if it sounds like a joke, it isn't - I would be very interested to see the alternative(s) :-)Habilitate
There are thread safe maps, for example, ones provided by junction library. Depending on the architecture of your app, it also may be possible to eliminate the global map and use other means of inter-thread communication, such as Qt signals.Sarcomatosis
L
6

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 !

Luigi answered 29/6, 2016 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.