Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C++ STL thread-safe for distinct containers (using STLport implementation)?

I'm using Android 2.2, which comes with a version of STLport. For some reason, it was configured to be non-thread safe. This was done using a #define _NOTHREADS in a configuration header file.

When I constructed and initialized distinct non-shared containers (e.g. strings) from different pthreads, I was getting memory corruption.

With _NOTHREADS, it looks like some low-level code in STL inside allocator.cpp doesn't do proper locking. It seems analogous to C not providing thread safety for malloc.

Does anyone know why STL might be built with _NOTHREADS by default on Android? By turning this off, I'm wondering if there may be a side effect. One thing I can think of is slightly degraded performance, but I don't see much of a choice given I'm using lots of threading.

like image 406
Ravi Avatar asked Dec 09 '10 23:12

Ravi


2 Answers

The SGI STL

The SGI STL is the grandmother of all of the other STL implementations.

See the SGI STL docs.

The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe. If multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses.

G++

libstdc++ docs

We currently use the SGI STL definition of thread safety.

STLPort

STLPort docs

Please refer to SGI site for detailed document on thread safety. Basic points are:

  • simultaneous read access to the same container from within separate threads is safe;
  • simultaneous access to distinct containers (not shared between threads) is safe;
  • user must provide synchronization for all accesses if any thread may modify shared container.
like image 116
Ken Bloom Avatar answered Sep 30 '22 09:09

Ken Bloom


General Information about the C++ Standard

The current C++ standard doesn't address concurrency issues at all, so at least for now there's no requirement that applies to all implementations.

A meaningful answer can only really apply to a specific implementation (STLPort, in this case). STLPort is basically a version of the original SGI STL implementation with improvements to its portability, so you'd probably want to start with the documentation about thread safety in the original SGI version.

like image 43
Jerry Coffin Avatar answered Sep 30 '22 08:09

Jerry Coffin