UsingCommand Options
The set of features available in the GNU C++ library is shaped by
several GCC
Command Options. Options that impact libstdc++ are
enumerated and detailed in the table below.
The standard library conforms to the dialect of C++ specified by the
option passed to the compiler.
By default, g++ is equivalent to
g++ -std=gnu++14 since GCC 6, and
g++ -std=gnu++98 for older releases.
C++ Command OptionsOption FlagsDescription-std=c++98 or -std=c++03Use the 1998 ISO C++ standard plus amendments.-std=gnu++98 or -std=gnu++03As directly above, with GNU extensions.-std=c++11Use the 2011 ISO C++ standard.-std=gnu++11As directly above, with GNU extensions.-std=c++14Use the 2014 ISO C++ standard.-std=gnu++14As directly above, with GNU extensions.-fexceptionsSee exception-free dialect-frttiAs above, but RTTI-free dialect.-pthreadFor ISO C++11
<thread>,
<future>,
<mutex>,
or <condition_variable>.
-latomicLinking to libatomic
is required for some uses of ISO C++11
<atomic>.
-lstdc++fsLinking to libstdc++fs
is required for use of the Filesystem library extensions in
<experimental/filesystem>.
-fopenmpFor parallel mode.
HeadersHeader Files
The C++ standard specifies the entire set of header files that
must be available to all hosted implementations. Actually, the
word "files" is a misnomer, since the contents of the
headers don't necessarily have to be in any kind of external
file. The only rule is that when one #includes a
header, the contents of that header become available, no matter
how.
That said, in practice files are used.
There are two main types of include files: header files related
to a specific version of the ISO C++ standard (called Standard
Headers), and all others (TS, TR1, C++ ABI, and Extensions).
Multiple dialects of standard headers are supported, corresponding to
the 1998 standard as updated for 2003, the 2011 standard, the 2014
standard, and so on.
and
and
show the C++98/03 include files.
These are available in the C++98 compilation mode,
i.e. -std=c++98 or -std=gnu++98.
Unless specified otherwise below, they are also available in later modes
(C++11, C++14 etc).
C++ 1998 Library Headersalgorithmbitsetcomplexdequeexceptionfstreamfunctionaliomanipiosiosfwdiostreamistreamiteratorlimitslistlocalemapmemorynewnumericostreamqueuesetsstreamstackstdexceptstreambufstringutilitytypeinfovalarrayvector
C++ 1998 Library Headers for C Library Facilitiescassertcerrnocctypecfloatciso646climitsclocalecmathcsetjmpcsignalcstdargcstddefcstdiocstdlibcstringctimecwcharcwctype
The following header is deprecated
and might be removed from a future C++ standard.
C++ 1998 Deprecated Library Headerstrstream
and
show the C++11 include files.
These are available in C++11 compilation
mode, i.e. -std=c++11 or -std=gnu++11.
Including these headers in C++98/03 mode may result in compilation errors.
Unless specified otherwise below, they are also available in later modes
(C++14 etc).
C++ 2011 Library Headersarrayatomicchronocodecvtcondition_variableforward_listfutureinitalizer_listmutexrandomratioregexscoped_allocatorsystem_errorthreadtupletypeindextype_traitsunordered_mapunordered_set
C++ 2011 Library Headers for C Library Facilitiesccomplexcfenvcinttypescstdaligncstdboolcstdintctgmathcuchar
shows the C++14 include file.
This is available in C++14 compilation
mode, i.e. -std=c++14 or -std=gnu++14.
Including this header in C++98/03 mode or C++11 will not result in
compilation errors, but will not define anything.
Unless specified otherwise below, it is also available in later modes
(C++17 etc).
C++ 2014 Library Headershared_mutex
shows the C++17 include files.
These are available in C++17 compilation
mode, i.e. -std=c++17 or -std=gnu++17.
Including these headers in earlier modes will not result in
compilation errors, but will not define anything.
Unless specified otherwise below, they are also available in later modes
(C++20 etc).
C++ 2017 Library Headersanyoptionalstring_viewvariant
,
shows the additional include file define by the
File System Technical Specification, ISO/IEC TS 18822.
This is available in C++11 and later compilation modes.
Including this header in earlier modes will not result in
compilation errors, but will not define anything.
File System TS Headerexperimental/filesystem
,
shows the additional include files define by the C++ Extensions for
Library Fundamentals Technical Specification, ISO/IEC TS 19568.
These are available in C++14 and later compilation modes.
Including these headers in earlier modes will not result in
compilation errors, but will not define anything.
C++ TR 1 Library Headerstr1/arraytr1/complextr1/memorytr1/functionaltr1/randomtr1/regextr1/tupletr1/type_traitstr1/unordered_maptr1/unordered_settr1/utility
C++ TR 1 Library Headers for C Library Facilitiestr1/ccomplextr1/cfenvtr1/cfloattr1/cmathtr1/cinttypestr1/climitstr1/cstdargtr1/cstdbooltr1/cstdinttr1/cstdiotr1/cstdlibtr1/ctgmathtr1/ctimetr1/cwchartr1/cwctype
Decimal floating-point arithmetic is available if the C++
compiler supports scalar decimal floating-point types defined via
__attribute__((mode(SD|DD|LD))).
C++ TR 24733 Decimal Floating-Point Headerdecimal/decimal
Also included are files for the C++ ABI interface:
Mixing Headers A few simple rules.
First, mixing different dialects of the standard headers is not
possible. It's an all-or-nothing affair. Thus, code like
#include <array>
#include <functional>
Implies C++11 mode. To use the entities in <array>, the C++11
compilation mode must be used, which implies the C++11 functionality
(and deprecations) in <functional> will be present.
Second, the other headers can be included with either dialect of
the standard headers, although features and types specific to C++11
are still only enabled when in C++11 compilation mode. So, to use
rvalue references with __gnu_cxx::vstring, or to use the
debug-mode versions of std::unordered_map, one must use
the std=gnu++11 compiler flag. (Or std=c++11, of course.)
A special case of the second rule is the mixing of TR1 and C++11
facilities. It is possible (although not especially prudent) to
include both the TR1 version and the C++11 version of header in the
same translation unit:
#include <tr1/type_traits>
#include <type_traits>
Several parts of C++11 diverge quite substantially from TR1 predecessors.
The C Headers and namespace std
The standard specifies that if one includes the C-style header
(<math.h> in this case), the symbols will be available
in the global namespace and perhaps in
namespace std:: (but this is no longer a firm
requirement.) On the other hand, including the C++-style
header (<cmath>) guarantees that the entities will be
found in namespace std and perhaps in the global namespace.
Usage of C++-style headers is recommended, as then
C-linkage names can be disambiguated by explicit qualification, such
as by std::abort. In addition, the C++-style headers can
use function overloading to provide a simpler interface to certain
families of C-functions. For instance in <cmath>, the
function std::sin has overloads for all the builtin
floating-point types. This means that std::sin can be
used uniformly, instead of a combination
of std::sinf, std::sin,
and std::sinl.
Precompiled HeadersThere are three base header files that are provided. They can be
used to precompile the standard headers and extensions into binary
files that may then be used to speed up compilations that use these headers.
stdc++.hIncludes all standard headers. Actual content varies depending on
language dialect.
stdtr1c++.hIncludes all of <stdc++.h>, and adds all the TR1 headers.
extc++.hIncludes all of <stdc++.h>, and adds all the Extension headers
(and in C++98 mode also adds all the TR1 headers by including all of
<stdtr1c++.h>).
To construct a .gch file from one of these base header files,
first find the include directory for the compiler. One way to do
this is:
g++ -v hello.cc
#include <...> search starts here:
/mnt/share/bld/H-x86-gcc.20071201/include/c++/4.3.0
...
End of search list.
Then, create a precompiled header file with the same flags that
will be used to compile other projects.
g++ -Winvalid-pch -x c++-header -g -O2 -o ./stdc++.h.gch /mnt/share/bld/H-x86-gcc.20071201/include/c++/4.3.0/x86_64-unknown-linux-gnu/bits/stdc++.h
The resulting file will be quite large: the current size is around
thirty megabytes. How to use the resulting file.
g++ -I. -include stdc++.h -H -g -O2 hello.cc
Verification that the PCH file is being used is easy:
g++ -Winvalid-pch -I. -include stdc++.h -H -g -O2 hello.cc -o test.exe
! ./stdc++.h.gch
. /mnt/share/bld/H-x86-gcc.20071201/include/c++/4.3.0/iostream
. /mnt/share/bld/H-x86-gcc.20071201include/c++/4.3.0/string
The exclamation point to the left of the stdc++.h.gch listing means that the generated PCH file was used. Detailed information about creating precompiled header files can be found in the GCC documentation.
Macros
All library macros begin with _GLIBCXX_.
Furthermore, all pre-processor macros, switches, and
configuration options are gathered in the
file c++config.h, which
is generated during the libstdc++ configuration and build
process. This file is then included when needed by files part of
the public libstdc++ API, like
<ios>. Most of these
macros should not be used by consumers of libstdc++, and are reserved
for internal implementation use. These macros cannot
be redefined.
A select handful of macros control libstdc++ extensions and extra
features, or provide versioning information for the API. Only
those macros listed below are offered for consideration by the
general public.
Below are the macros which users may check for library version
information. _GLIBCXX_RELEASEThe major release number for libstdc++. This macro is defined
to the GCC major version that the libstdc++ headers belong to,
as an integer constant.
When compiling with GCC it has the same value as GCC's pre-defined
macro __GNUC__.
This macro can be used when libstdc++ is used with a non-GNU
compiler where __GNUC__ is not defined, or has a
different value that doesn't correspond to the libstdc++ version.
This macro first appeared in the GCC 7.1 release and is not defined
for GCC 6.x or older releases.
__GLIBCXX__The revision date of the libstdc++ source code,
in compressed ISO date format, as an unsigned
long. For notes about using this macro and details on the value of
this macro for a particular release, please consult the
ABI History
appendix.
Below are the macros which users may change with #define/#undef or
with -D/-U compiler flags. The default state of the symbol is
listed.Configurable (or Not configurable) means
that the symbol is initially chosen (or not) based on
--enable/--disable options at library build and configure time
(documented in
Configure),
with the various --enable/--disable choices being translated to
#define/#undef).
ABI means that changing from the default value may
mean changing the ABI of compiled code. In other words,
these choices control code which has already been compiled (i.e., in a
binary such as libstdc++.a/.so). If you explicitly #define or
#undef these macros, the headers may see different code
paths, but the libraries which you link against will not.
Experimenting with different values with the expectation of
consistent linkage requires changing the config headers before
building/installing the library.
_GLIBCXX_USE_DEPRECATED
Defined by default. Not configurable. ABI-changing. Turning this off
removes older ARM-style iostreams code, and other anachronisms
from the API. This macro is dependent on the version of the
standard being tracked, and as a result may give different results for
-std=c++98 and -std=c++11. This may
be useful in updating old C++ code which no longer meet the
requirements of the language, or for checking current code
against new language standards.
_GLIBCXX_USE_CXX11_ABI
Defined to the value 1 by default.
Configurable via --disable-libstdcxx-dual-abi
and/or --with-default-libstdcxx-abi.
ABI-changing.
When defined to a non-zero value the library headers will use the
new C++11-conforming ABI introduced in GCC 5, rather than the older
ABI introduced in GCC 3.4. This changes the definition of several
class templates, including std:string,
std::list and some locale facets.
For more details see .
_GLIBCXX_CONCEPT_CHECKS
Undefined by default. Configurable via
--enable-concept-checks. When defined, performs
compile-time checking on certain template instantiations to
detect violations of the requirements of the standard. This
macro has no effect for freestanding implementations.
This is described in more detail in
Compile Time Checks.
_GLIBCXX_ASSERTIONS
Undefined by default. When defined, enables extra error checking in
the form of precondition assertions, such as bounds checking in
strings and null pointer checks when dereferencing smart pointers.
_GLIBCXX_DEBUG
Undefined by default. When defined, compiles user code using
the debug mode.
When defined, _GLIBCXX_ASSERTIONS is defined
automatically, so all the assertions enabled by that macro are also
enabled in debug mode.
_GLIBCXX_DEBUG_PEDANTIC
Undefined by default. When defined while compiling with
the debug mode, makes
the debug mode extremely picky by making the use of libstdc++
extensions and libstdc++-specific behavior into errors.
_GLIBCXX_PARALLELUndefined by default. When defined, compiles user code
using the parallel
mode.
_GLIBCXX_PARALLEL_ASSERTIONSUndefined by default, but when any parallel mode header is included
this macro will be defined to a non-zero value if
_GLIBCXX_ASSERTIONS has a non-zero value, otherwise to zero.
When defined to a non-zero value, it enables extra error checking and
assertions in the parallel mode.
_GLIBCXX_PROFILEUndefined by default. When defined, compiles user code
using the profile
mode.
__STDCPP_WANT_MATH_SPEC_FUNCS__Undefined by default. When defined to a non-zero integer constant,
enables support for ISO/IEC 29124 Special Math Functions.
Dual ABI In the GCC 5.1 release libstdc++ introduced a new library ABI that
includes new implementations of std::string and
std::list. These changes were necessary to conform
to the 2011 C++ standard which forbids Copy-On-Write strings and requires
lists to keep track of their size.
In order to maintain backwards compatibility for existing code linked
to libstdc++ the library's soname has not changed and the old
implementations are still supported in parallel with the new ones.
This is achieved by defining the new implementations in an inline namespace
so they have different names for linkage purposes, e.g. the new version of
std::list<int> is actually defined as
std::__cxx11::list<int>. Because the symbols
for the new implementations have different names the definitions for both
versions can be present in the same library.
The _GLIBCXX_USE_CXX11_ABI macro (see
) controls whether
the declarations in the library headers use the old or new ABI.
So the decision of which ABI to use can be made separately for each
source file being compiled.
Using the default configuration options for GCC the default value
of the macro is 1 which causes the new ABI to be active,
so to use the old ABI you must explicitly define the macro to
0 before including any library headers.
(Be aware that some GNU/Linux distributions configure GCC 5 differently so
that the default value of the macro is 0 and users must
define it to 1 to enable the new ABI.)
Although the changes were made for C++11 conformance, the choice of ABI
to use is independent of the option used to compile
your code, i.e. for a given GCC build the default value of the
_GLIBCXX_USE_CXX11_ABI macro is the same for all dialects.
This ensures that the does not change the ABI, so
that it is straightforward to link C++03 and C++11 code together.
Because std::string is used extensively
throughout the library a number of other types are also defined twice,
including the stringstream classes and several facets used by
std::locale. The standard facets which are always
installed in a locale may be present twice, with both ABIs, to ensure that
code like
std::use_facet<std::time_get<char>>(locale);
will work correctly for both std::time_get and
std::__cxx11::time_get (even if a user-defined
facet that derives from one or other version of
time_get is installed in the locale).
Although the standard exception types defined in
<stdexcept> use strings, most
are not defined twice, so that a std::out_of_range
exception thrown in one file can always be caught by a suitable handler in
another file, even if the two files are compiled with different ABIs.
One exception type does change when using the new ABI, namely
std::ios_base::failure.
This is necessary because the 2011 standard changed its base class from
std::exception to
std::system_error, which causes its layout to change.
Exceptions due to iostream errors are thrown by a function inside
libstdc++.so, so whether the thrown
exception uses the old std::ios_base::failure type
or the new one depends on the ABI that was active when
libstdc++.so was built,
not the ABI active in the user code that is using
iostreams.
This means that for a given build of GCC the type thrown is fixed.
In current releases the library throws a special type that can be caught
by handlers for either the old or new type,
but for GCC 7.1, 7.2 and 7.3 the library throws the new
std::ios_base::failure type,
and for GCC 5.x and 6.x the library throws the old type.
Catch handlers of type std::ios_base::failure
will only catch the exceptions if using a newer release,
or if the handler is compiled with the same ABI as the type thrown by
the library.
Handlers for std::exception will always catch
iostreams exceptions, because the old and new type both inherit from
std::exception.
Troubleshooting If you get linker errors about undefined references to symbols
that involve types in the std::__cxx11 namespace or the tag
[abi:cxx11] then it probably indicates that you are trying to
link together object files that were compiled with different values for the
_GLIBCXX_USE_CXX11_ABI macro. This commonly happens when
linking to a third-party library that was compiled with an older version
of GCC. If the third-party library cannot be rebuilt with the new ABI then
you will need to recompile your code with the old ABI.
Not all uses of the new ABI will cause changes in symbol names, for
example a class with a std::string member variable
will have the same mangled name whether compiled with the old or new ABI.
In order to detect such problems the new types and functions are
annotated with the abi_tag attribute, allowing the
compiler to warn about potential ABI incompatibilities in code using them.
Those warnings can be enabled with the option.
NamespacesAvailable Namespaces There are three main namespaces.
stdThe ISO C++ standards specify that "all library entities are defined
within namespace std." This includes namespaces nested
within namespace std, such as namespace
std::chrono.
abiSpecified by the C++ ABI. This ABI specifies a number of type and
function APIs supplemental to those required by the ISO C++ Standard,
but necessary for interoperability.
__gnu_Indicating one of several GNU extensions. Choices
include __gnu_cxx, __gnu_debug, __gnu_parallel,
and __gnu_pbds.
The library uses a number of inline namespaces as implementation
details that are not intended for users to refer to directly, these include
std::__detail, std::__cxx11 and std::_V2.
A complete list of implementation namespaces (including namespace contents) is available in the generated source documentation.
namespace std
One standard requirement is that the library components are defined
in namespace std::. Thus, in order to use these types or
functions, one must do one of two things:
put a kind of using-declaration in your source
(either using namespace std; or i.e. using
std::string;) This approach works well for individual source files, but
should not be used in a global context, like header files.
use a fully
qualified name for each library symbol
(i.e. std::string, std::cout) Always can be
used, and usually enhanced, by strategic use of typedefs. (In the
cases where the qualified verbiage becomes unwieldy.)
Using Namespace Composition
Best practice in programming suggests sequestering new data or
functionality in a sanely-named, unique namespace whenever
possible. This is considered an advantage over dumping everything in
the global namespace, as then name look-up can be explicitly enabled or
disabled as above, symbols are consistently mangled without repetitive
naming prefixes or macros, etc.
For instance, consider a project that defines most of its classes in namespace gtk. It is possible to
adapt namespace gtk to namespace std by using a C++-feature called
namespace composition. This is what happens if
a using-declaration is put into a
namespace-definition: the imported symbol(s) gets imported into the
currently active namespace(s). For example:
namespace gtk
{
using std::string;
using std::tr1::array;
class Window { ... };
}
In this example, std::string gets imported into
namespace gtk. The result is that use of
std::string inside namespace gtk can just use string, without the explicit qualification.
As an added bonus,
std::string does not get imported into
the global namespace. Additionally, a more elaborate arrangement can be made for backwards compatibility and portability, whereby the
using-declarations can wrapped in macros that
are set based on autoconf-tests to either "" or i.e. using
std::string; (depending on whether the system has
libstdc++ in std:: or not). (ideas from
Llewelly and Karl Nelson)
LinkingAlmost Nothing
Or as close as it gets: freestanding. This is a minimal
configuration, with only partial support for the standard
library. Assume only the following header files can be used:
cstdargcstddefcstdlibexceptionlimitsnewexceptiontypeinfo
In addition, throw in
cxxabi.h.
In the
C++11 dialect add
initializer_listtype_traits There exists a library that offers runtime support for
just these headers, and it is called
libsupc++.a. To use it, compile with gcc instead of g++, like so:
gcc foo.cc -lsupc++
No attempt is made to verify that only the minimal subset
identified above is actually used at compile time. Violations
are diagnosed as undefined symbols at link time.
Finding Dynamic or Shared Libraries
If the only library built is the static library
(libstdc++.a), or if
specifying static linking, this section is can be skipped. But
if building or using a shared library
(libstdc++.so), then
additional location information will need to be provided.
But how?
A quick read of the relevant part of the GCC
manual, Compiling
C++ Programs, specifies linking against a C++
library. More details from the
GCC FAQ,
which states GCC does not, by default, specify a
location so that the dynamic linker can find dynamic libraries at
runtime.
Users will have to provide this information.
Methods vary for different platforms and different styles, and
are printed to the screen during installation. To summarize:
At runtime set LD_LIBRARY_PATH in your
environment correctly, so that the shared library for
libstdc++ can be found and loaded. Be certain that you
understand all of the other implications and behavior
of LD_LIBRARY_PATH first.
Compile the path to find the library at runtime into the
program. This can be done by passing certain options to
g++, which will in turn pass them on to
the linker. The exact format of the options is dependent on
which linker you use:
GNU ld (default on GNU/Linux):
-Wl,-rpath,destdir/lib
Solaris ld:
-Wl,-Rdestdir/lib
Some linkers allow you to specify the path to the library by
setting LD_RUN_PATH in your environment
when linking.
On some platforms the system administrator can configure the
dynamic linker to always look for libraries in
destdir/lib, for example
by using the ldconfig utility on GNU/Linux
or the crle utility on Solaris. This is a
system-wide change which can make the system unusable so if you
are unsure then use one of the other methods described above.
Use the ldd utility on the linked executable
to show
which libstdc++.so
library the system will get at runtime.
A libstdc++.la file is
also installed, for use with Libtool. If you use Libtool to
create your executables, these details are taken care of for
you.
Experimental Library Extensions
GCC 5.3 includes an implementation of the Filesystem library defined
by the technical specification ISO/IEC TS 18822:2015. Because this is
an experimental library extension, not part of the C++ standard, it
is implemented in a separate library,
libstdc++fs.a, and there is
no shared library for it. To use the library you should include
<experimental/filesystem>
and link with . The library implementation
is incomplete on non-POSIX platforms, specifically Windows support is
rudimentary.
Due to the experimental nature of the Filesystem library the usual
guarantees about ABI stability and backwards compatibility do not apply
to it. There is no guarantee that the components in any
<experimental/xxx>
header will remain compatible between different GCC releases.
ConcurrencyThis section discusses issues surrounding the proper compilation
of multithreaded applications which use the Standard C++
library. This information is GCC-specific since the C++
standard does not address matters of multithreaded applications.
PrerequisitesAll normal disclaimers aside, multithreaded C++ application are
only supported when libstdc++ and all user code was built with
compilers which report (via gcc/g++ -v ) the same thread
model and that model is not single. As long as your
final application is actually single-threaded, then it should be
safe to mix user code built with a thread model of
single with a libstdc++ and other C++ libraries built
with another thread model useful on the platform. Other mixes
may or may not work but are not considered supported. (Thus, if
you distribute a shared C++ library in binary form only, it may
be best to compile it with a GCC configured with
--enable-threads for maximal interchangeability and usefulness
with a user population that may have built GCC with either
--enable-threads or --disable-threads.)
When you link a multithreaded application, you will probably
need to add a library or flag to g++. This is a very
non-standardized area of GCC across ports. Some ports support a
special flag (the spelling isn't even standardized yet) to add
all required macros to a compilation (if any such flags are
required then you must provide the flag for all compilations not
just linking) and link-library additions and/or replacements at
link time. The documentation is weak. On several targets (including
GNU/Linux, Solaris and various BSDs) -pthread is honored.
Some other ports use other switches.
This is not well documented anywhere other than
in "gcc -dumpspecs" (look at the 'lib' and 'cpp' entries).
Some uses of std::atomic also require linking
to libatomic.
Thread Safety
In the terms of the 2011 C++ standard a thread-safe program is one which
does not perform any conflicting non-atomic operations on memory locations
and so does not contain any data races.
The standard places requirements on the library to ensure that no data
races are caused by the library itself or by programs which use the
library correctly (as described below).
The C++11 memory model and library requirements are a more formal version
of the SGI STL definition of thread safety, which the library used
prior to the 2011 standard.
The library strives to be thread-safe when all of the following
conditions are met:
The system's libc is itself thread-safe,
The compiler in use reports a thread model other than
'single'. This can be tested via output from gcc
-v. Multi-thread capable versions of gcc output
something like this:
%gcc -v
Using built-in specs.
...
Thread model: posix
gcc version 4.1.2 20070925 (Red Hat 4.1.2-33)
Look for "Thread model" lines that aren't equal to "single."
Requisite command-line flags are used for atomic operations
and threading. Examples of this include -pthread
and -march=native, although specifics vary
depending on the host environment. See
Command Options and
Machine
Dependent Options.
An implementation of the
atomicity.h functions
exists for the architecture in question. See the
internals
documentation for more details.
The user code must guard against concurrent function calls which
access any particular library object's state when one or more of
those accesses modifies the state. An object will be modified by
invoking a non-const member function on it or passing it as a
non-const argument to a library function. An object will not be
modified by invoking a const member function on it or passing it to
a function as a pointer- or reference-to-const.
Typically, the application
programmer may infer what object locks must be held based on the
objects referenced in a function call and whether the objects are
accessed as const or non-const. Without getting
into great detail, here is an example which requires user-level
locks:
library_class_a shared_object_a;
void thread_main () {
library_class_b *object_b = new library_class_b;
shared_object_a.add_b (object_b); // must hold lock for shared_object_a
shared_object_a.mutate (); // must hold lock for shared_object_a
}
// Multiple copies of thread_main() are started in independent threads.Under the assumption that object_a and object_b are never exposed to
another thread, here is an example that does not require any
user-level locks:
void thread_main () {
library_class_a object_a;
library_class_b *object_b = new library_class_b;
object_a.add_b (object_b);
object_a.mutate ();
} All library types are safe to use in a multithreaded program
if objects are not shared between threads or as
long each thread carefully locks out access by any other
thread while it modifies any object visible to another thread.
Unless otherwise documented, the only exceptions to these rules
are atomic operations on the types in
<atomic>
and lock/unlock operations on the standard mutex types in
<mutex>. These
atomic operations allow concurrent accesses to the same object
without introducing data races.
The following member functions of standard containers can be
considered to be const for the purposes of avoiding data races:
begin, end, rbegin, rend,
front, back, data,
find, lower_bound, upper_bound,
equal_range, at
and, except in associative or unordered associative containers,
operator[]. In other words, although they are non-const
so that they can return mutable iterators, those member functions
will not modify the container.
Accessing an iterator might cause a non-modifying access to
the container the iterator refers to (for example incrementing a
list iterator must access the pointers between nodes, which are part
of the container and so conflict with other accesses to the container).
Programs which follow the rules above will not encounter data
races in library code, even when using library types which share
state between distinct objects. In the example below the
shared_ptr objects share a reference count, but
because the code does not perform any non-const operations on the
globally-visible object, the library ensures that the reference
count updates are atomic and do not introduce data races:
std::shared_ptr<int> global_sp;
void thread_main() {
auto local_sp = global_sp; // OK, copy constructor's parameter is reference-to-const
int i = *global_sp; // OK, operator* is const
int j = *local_sp; // OK, does not operate on global_sp
// *global_sp = 2; // NOT OK, modifies int visible to other threads
// *local_sp = 2; // NOT OK, modifies int visible to other threads
// global_sp.reset(); // NOT OK, reset is non-const
local_sp.reset(); // OK, does not operate on global_sp
}
int main() {
global_sp.reset(new int(1));
std::thread t1(thread_main);
std::thread t2(thread_main);
t1.join();
t2.join();
}
For further details of the C++11 memory model see Hans-J. Boehm's
Threads
and memory model for C++ pages, particularly the introduction
and FAQ.
AtomicsIOThis gets a bit tricky. Please read carefully, and bear with me.
StructureA wrapper
type called __basic_file provides our abstraction layer
for the std::filebuf classes. Nearly all decisions dealing
with actual input and output must be made in __basic_file.
A generic locking mechanism is somewhat in place at the filebuf layer,
but is not used in the current code. Providing locking at any higher
level is akin to providing locking within containers, and is not done
for the same reasons (see the links above).
DefaultsThe __basic_file type is simply a collection of small wrappers around
the C stdio layer (again, see the link under Structure). We do no
locking ourselves, but simply pass through to calls to fopen,
fwrite, and so forth.
So, for 3.0, the question of "is multithreading safe for I/O"
must be answered with, "is your platform's C library threadsafe
for I/O?" Some are by default, some are not; many offer multiple
implementations of the C library with varying tradeoffs of threadsafety
and efficiency. You, the programmer, are always required to take care
with multiple threads.
(As an example, the POSIX standard requires that C stdio
FILE* operations are atomic. POSIX-conforming C libraries
(e.g, on Solaris and GNU/Linux) have an internal mutex to serialize
operations on FILE*s.
However, you still need to not do stupid things like calling
fclose(fs) in one thread followed by an access of
fs in another.)
So, if your platform's C library is threadsafe, then your
fstream I/O operations will be threadsafe at the lowest
level. For higher-level operations, such as manipulating the data
contained in the stream formatting classes (e.g., setting up callbacks
inside an std::ofstream), you need to guard such accesses
like any other critical shared resource.
Future A
second choice may be available for I/O implementations: libio. This is
disabled by default, and in fact will not currently work due to other
issues. It will be revisited, however.
The libio code is a subset of the guts of the GNU libc (glibc) I/O
implementation. When libio is in use, the __basic_file
type is basically derived from FILE. (The real situation is more
complex than that... it's derived from an internal type used to
implement FILE. See libio/libioP.h to see scary things done with
vtbls.) The result is that there is no "layer" of C stdio
to go through; the filebuf makes calls directly into the same
functions used to implement fread, fwrite,
and so forth, using internal data structures. (And when I say
"makes calls directly," I mean the function is literally
replaced by a jump into an internal function. Fast but frightening.
*grin*)
Also, the libio internal locks are used. This requires pulling in
large chunks of glibc, such as a pthreads implementation, and is one
of the issues preventing widespread use of libio as the libstdc++
cstdio implementation.
But we plan to make this work, at least as an option if not a future
default. Platforms running a copy of glibc with a recent-enough
version will see calls from libstdc++ directly into the glibc already
installed. For other platforms, a copy of the libio subsection will
be built and included in libstdc++.
AlternativesDon't forget that other cstdio implementations are possible. You could
easily write one to perform your own forms of locking, to solve your
"interesting" problems.
ContainersThis section discusses issues surrounding the design of
multithreaded applications which use Standard C++ containers.
All information in this section is current as of the gcc 3.0
release and all later point releases. Although earlier gcc
releases had a different approach to threading configuration and
proper compilation, the basic code design rules presented here
were similar. For information on all other aspects of
multithreading as it relates to libstdc++, including details on
the proper compilation of threaded code (and compatibility between
threaded and non-threaded code), see Chapter 17.
Two excellent pages to read when working with the Standard C++
containers and threads are
SGI's
http://www.sgi.com/tech/stl/thread_safety.html and
SGI's
http://www.sgi.com/tech/stl/Allocators.html.
However, please ignore all discussions about the user-level
configuration of the lock implementation inside the STL
container-memory allocator on those pages. For the sake of this
discussion, libstdc++ configures the SGI STL implementation,
not you. This is quite different from how gcc pre-3.0 worked.
In particular, past advice was for people using g++ to
explicitly define _PTHREADS or other macros or port-specific
compilation options on the command line to get a thread-safe
STL. This is no longer required for any port and should no
longer be done unless you really know what you are doing and
assume all responsibility.Since the container implementation of libstdc++ uses the SGI
code, we use the same definition of thread safety as SGI when
discussing design. A key point that beginners may miss is the
fourth major paragraph of the first page mentioned above
(For most clients...), which points out that
locking must nearly always be done outside the container, by
client code (that'd be you, not us). There is a notable
exceptions to this rule. Allocators called while a container or
element is constructed uses an internal lock obtained and
released solely within libstdc++ code (in fact, this is the
reason STL requires any knowledge of the thread configuration).
For implementing a container which does its own locking, it is
trivial to provide a wrapper class which obtains the lock (as
SGI suggests), performs the container operation, and then
releases the lock. This could be templatized to a certain
extent, on the underlying container and/or a locking
mechanism. Trying to provide a catch-all general template
solution would probably be more trouble than it's worth.
The library implementation may be configured to use the
high-speed caching memory allocator, which complicates thread
safety issues. For all details about how to globally override
this at application run-time
see here. Also
useful are details
on allocator
options and capabilities.