Previous: The Gnulib multithreading API, Up: Multithreading [Contents][Index]
Despite all the optimizations of multithreading primitives that have been implemented over the years – from atomic operations in hardware, over futexes and restartable sequences in the Linux kernel, to lock elision [1] [2]) – single-threaded programs can still profit performance-wise from the assertion that they are single-threaded.
Gnulib defines four facilities that help optimizing for the single-threaded case.
libpthread
. If not, the program has no way to create additional
threads and must therefore be single-threaded. This optimization applies
to all the Gnulib multithreading API (locks, thread-local storage, and more).
thread-optim
module, on glibc ≥ 2.32 systems, allows your code
to skip locking between threads (regardless which of the three multithreading
APIs you use). You need extra code for this: include the
"thread-optim.h"
header file, and use the macro gl_multithreaded
like this:
bool mt = gl_multithreaded (); if (mt) gl_lock_lock (some_lock); ... if (mt) gl_lock_unlock (some_lock);
unlocked-io
module if you want the FILE
stream
functions getc
, putc
, etc. to use unlocked I/O if available,
throughout the package. Unlocked I/O can improve performance, sometimes
dramatically. But unlocked I/O is safe only in single-threaded programs,
as well as in multithreaded programs for which you can guarantee that
every FILE
stream, including stdin
, stdout
, stderr
,
is used only in a single thread.
You need extra code for this optimization to be effective: include the
"unlocked-io.h"
header file. Some Gnulib modules that do operations
on FILE
streams have these preparations already included.
GNULIB_REGEX_SINGLE_THREAD
, if all the
programs in your package invoke the functions of the regex
module
only from a single thread.
GNULIB_MBRTOWC_SINGLE_THREAD
, if all the
programs in your package invoke the functions mbrtowc
, mbrtoc32
,
and the functions of the regex
module only from a single thread. (The
regex
module uses mbrtowc
under the hood.)
GNULIB_WCHAR_SINGLE_LOCALE
, if all the
programs in your package set the locale early and
mbrtowc
, wcwidth
, etc.)
before the locale has been initialized.
This macro optimizes the functions mbrtowc
, mbrtoc32
, and
wcwidth
.
You can get this macro defined by including the Gnulib module
wchar-single
.
GNULIB_EXCLUDE_SINGLE_THREAD
, if all the
programs in your package invoke the functions of the exclude
module
only from a single thread.
Previous: The Gnulib multithreading API, Up: Multithreading [Contents][Index]