thread-optim.h 2.1 KB

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