[Interest] QMap and thread-safe.

Thiago Macieira thiago.macieira at intel.com
Thu Jul 25 07:06:37 CEST 2013


On quinta-feira, 25 de julho de 2013 10:00:20, Mandeep Sandhu wrote:
> What I meant with "it applies to C++11", is that the C++11 standard library
> now follows/respects the correct meaning of "const", i.e all std lib's
> const functions are thread safe and in turn they expect "user" defined
> const functions to be thread-safe as well.

Ah, that changes things. Yes, if the Standard Library now enforces "const 
member" = thread-safe, that's great. It is how the Qt value-type classes have 
behaved since Qt 4.0, even though we haven't documented that.

The big question is whether they're thread-safe among themselves, or if they 
are thread-safe even if another thread is calling a non-const method.

I would not expect the latter case. It's extremely hard to do and, to be 
honest, does not have much value. One thing that we tell people is to treat 
the Qt value-type containers as they'd treat an "int" or "char". In that case, 
if we apply the same logic about "const container" to "const int", for which 
many reads are thread-safe, as long as no thread is doing a write, then the 
const methods are thread-safe as long as no non-const method is called.

> > very easy to break out of the safety:
> >         const_cast
> >         mutable
> 
> But having a mutable in a const function is (logiaclly) right. Rather thats
> how, Herb explains, one would implement a thread-safe const function.
> 
> On the other hand doing a const_cast, in a const function, looked more of a
> work-around to make the compiler happy.

Both mean the same thing: they allow you to modify the internals inside a 
const method. If you don't do it carefully, you can cause problems.

Take a very simple case of mutable:

class String
{
    ushort *utf16;
    mutable char *cached_latin1;

public:
    char *latin1() const
    { if (!cached_latin1) cached_latin1 = toLatin1(); return cached_latin1; }
};

The function above is not thread-safe. If two threads at the same time call 
that function while cached_latin1 is null, both of them might allocate memory 
and one of them will probably leak the other's pointer.

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel Open Source Technology Center
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20130724/5d01ae8e/attachment.sig>


More information about the Interest mailing list