help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: STL and multithreading


From: Paul Pluzhnikov
Subject: Re: STL and multithreading
Date: Mon, 24 Sep 2007 21:52:41 -0700
User-agent: Gnus/5.1006 (Gnus v5.10.6) XEmacs/21.4 (Jumbo Shrimp, linux)

Carlos Martinez <carlos.mtnez@gmail.com> writes:

> I want to know if gnu g++'s STL implementation is thread safe or not.

Yes, for some definition of thread-safe.

In particular, it is safe to create/use any STL item in a single
thread, but it is not safe to "share" any of them between multiple
threads without proper locking.

> Initially I suppose that protecting all access to an STL containter
> with mutexes, I can resolve the problem, 

Which problem?

> but I have a doubt about it: Memory allocation.

What about it? Memory allocation itself (malloc, new, etc.) is
thread-safe on all platforms that support threads.

> I can protect with a mutex access to a resource (for example an STL
> container), but the default allocator can be accessed concurrently
> from several containers and/or instances of a concrete container, and
> I haven't the control of it.

You'll find that most std::allocator's default to __malloc_alloc_template,
which is thread-safe because malloc is, or new_allocator (also safe
for the same reason). Some versions of gcc (as shipped by RedHat)
default to __mt_alloc, which is explicitly MT-safe.

If you override the default, it's up to you to make sure it is
thread-safe.

> There are other techniques for efficiency, as sharing implementation
> (with reference counting) that I suppose that can have problems with
> multithreading but I don't know if g++'s STL implementation uses that
> kind of techniques.

Yes, reference counts are still used (especially for empty strings),
but should be done in thread-safe way if your platform defaults to
"thread-enabled" gcc (Linux does).

Cheers,
-- 
In order to understand recursion you must first understand recursion.
Remove /-nsp/ for email.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]