5

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?

scuberula
  • 35
  • 1
  • 10
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
  • QMap is "reentrant" defined here: http://doc.qt.io/qt-4.8/threads-reentrancy.html#reentrant . My conclusion is NOT thread safe. ie 1) No, 2) No. – Richard Critten Jun 29 '16 at 12:24
  • Not thread safe, insertions and removal modify the container, regardless of the specific index you are working on. – Emerald Weapon Jun 29 '16 at 12:25
  • 1
    Yes, the simplest solution is to guard access to the map with a mutex. – Pavel Strakhov Jun 29 '16 at 13:04
  • @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) :-) – סטנלי גרונן Jun 29 '16 at 13:30
  • There are thread safe maps, for example, ones provided by [junction](https://github.com/preshing/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. – Pavel Strakhov Jun 29 '16 at 13:37

1 Answers1

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 !

N0un
  • 868
  • 8
  • 31