| 1 | /* Optimization of multithreaded code.
|
|---|
| 2 |
|
|---|
| 3 | Copyright (C) 2020-2022 Free Software Foundation, Inc.
|
|---|
| 4 |
|
|---|
| 5 | This file is free software: you can redistribute it and/or modify
|
|---|
| 6 | it under the terms of the GNU Lesser General Public License as
|
|---|
| 7 | published by the Free Software Foundation; either version 2.1 of the
|
|---|
| 8 | License, or (at your option) any later version.
|
|---|
| 9 |
|
|---|
| 10 | This file is distributed in the hope that it will be useful,
|
|---|
| 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|---|
| 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|---|
| 13 | GNU Lesser General Public License for more details.
|
|---|
| 14 |
|
|---|
| 15 | You should have received a copy of the GNU Lesser General Public License
|
|---|
| 16 | along with this program. If not, see <https://www.gnu.org/licenses/>. */
|
|---|
| 17 |
|
|---|
| 18 | /* Written by Bruno Haible <bruno@clisp.org>, 2020. */
|
|---|
| 19 |
|
|---|
| 20 | #ifndef _THREAD_OPTIM_H
|
|---|
| 21 | #define _THREAD_OPTIM_H
|
|---|
| 22 |
|
|---|
| 23 | /* This file defines a way to optimize multithreaded code for the single-thread
|
|---|
| 24 | case, based on the variable '__libc_single_threaded', defined in
|
|---|
| 25 | glibc >= 2.32. */
|
|---|
| 26 |
|
|---|
| 27 | /* Typical use: In a block or function, use
|
|---|
| 28 |
|
|---|
| 29 | bool mt = gl_multithreaded ();
|
|---|
| 30 | ...
|
|---|
| 31 | if (mt)
|
|---|
| 32 | if (pthread_mutex_lock (&lock)) abort ();
|
|---|
| 33 | ...
|
|---|
| 34 | if (mt)
|
|---|
| 35 | if (pthread_mutex_unlock (&lock)) abort ();
|
|---|
| 36 |
|
|---|
| 37 | The gl_multithreaded () invocation determines whether the program currently
|
|---|
| 38 | is multithreaded.
|
|---|
| 39 |
|
|---|
| 40 | if (mt) STATEMENT executes STATEMENT in the multithreaded case, and skips
|
|---|
| 41 | it in the single-threaded case.
|
|---|
| 42 |
|
|---|
| 43 | The code between the gl_multithreaded () invocation and any use of the
|
|---|
| 44 | variable 'mt' must not create threads or invoke functions that may
|
|---|
| 45 | indirectly create threads (e.g. 'dlopen' may, indirectly through C++
|
|---|
| 46 | initializers of global variables in the shared library being opened,
|
|---|
| 47 | create threads).
|
|---|
| 48 |
|
|---|
| 49 | The lock here is meant to synchronize threads in the same process. The
|
|---|
| 50 | same optimization cannot be applied to locks that synchronize different
|
|---|
| 51 | processes (e.g. through shared memory mappings). */
|
|---|
| 52 |
|
|---|
| 53 | #if HAVE_SYS_SINGLE_THREADED_H /* glibc >= 2.32 */
|
|---|
| 54 | # include <sys/single_threaded.h>
|
|---|
| 55 | # define gl_multithreaded() (!__libc_single_threaded)
|
|---|
| 56 | #else
|
|---|
| 57 | # define gl_multithreaded() 1
|
|---|
| 58 | #endif
|
|---|
| 59 |
|
|---|
| 60 | #endif /* _THREAD_OPTIM_H */
|
|---|