FindThreads.cmake 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file LICENSE.rst or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. FindThreads
  5. -----------
  6. Finds and determines the thread library of the system for multithreading
  7. support:
  8. .. code-block:: cmake
  9. find_package(Threads [...])
  10. Multithreading enables concurrent execution within a single program,
  11. typically by creating multiple threads of execution. Most commonly, this
  12. is done using libraries such as POSIX Threads (``pthreads``) on Unix-like
  13. systems or Windows threads on Windows.
  14. This module abstracts the platform-specific differences and detects how to
  15. enable thread support - whether it requires linking to a specific library,
  16. adding compiler flags (like ``-pthread``), or both. On some platforms,
  17. threading is also implicitly available in default libraries without the
  18. need to use additional flags or libraries.
  19. This module is suitable for use in both C and C++ projects (and occasionally
  20. other compiled languages) that rely on system-level threading APIs.
  21. Using this module ensures that project builds correctly across different
  22. platforms by handling the detection and setup of thread support in a
  23. portable way.
  24. C and C++ Language Standards
  25. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  26. The C11 standard introduced a minimal cross-platform thread API via
  27. ``<threads.h>`` header file, and C++11 added ``<thread>`` header to the
  28. standard library, offering high-level multithreading support. These standard
  29. headers allow writing portable threaded code at the language level, without
  30. directly using platform-specific APIs like ``pthreads`` or Windows threads.
  31. However, even with standard C11 or C++11 threads support available, there
  32. may still be a need for platform-specific compiler or linker flags (e.g.,
  33. ``-pthread`` on Unix-like systems) for some applications. This is where
  34. FindThreads remains relevant - it ensures these flags and any required
  35. libraries are correctly set up, even if not explicitly using system APIs.
  36. In short:
  37. * Use ``<thread>`` (C++11 and later) or ``<threads.h>`` (C11) in source code
  38. for portability and simpler syntax.
  39. * Use ``find_package(Threads)`` in CMake project when application needs the
  40. traditional threading support and to ensure code compiles and links
  41. correctly across different platforms.
  42. Imported Targets
  43. ^^^^^^^^^^^^^^^^
  44. This module provides the following :ref:`Imported Targets`:
  45. ``Threads::Threads``
  46. .. versionadded:: 3.1
  47. Target encapsulating the usage requirements to enable threading through
  48. flags or a threading library, if found. This target is available if
  49. threads are detected as supported.
  50. Result Variables
  51. ^^^^^^^^^^^^^^^^
  52. This module defines the following variables:
  53. ``Threads_FOUND``
  54. Boolean indicating whether Threads is supported, either through a separate
  55. library or a standard library.
  56. ``CMAKE_THREAD_LIBS_INIT``
  57. The thread library to use. This may be empty if the thread functions
  58. are provided by the system libraries and no special flags are needed
  59. to use them.
  60. ``CMAKE_USE_WIN32_THREADS_INIT``
  61. If the found thread library is the win32 one.
  62. ``CMAKE_USE_PTHREADS_INIT``
  63. If the found thread library is pthread compatible.
  64. ``CMAKE_HP_PTHREADS_INIT``
  65. If the found thread library is the HP thread library.
  66. Variables Affecting Behavior
  67. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  68. This module accepts the following variables before calling
  69. ``find_package(Threads)``:
  70. ``THREADS_PREFER_PTHREAD_FLAG``
  71. .. versionadded:: 3.1
  72. If the use of the ``-pthread`` compiler and linker flag is preferred then
  73. the caller can set this variable to boolean true. The compiler flag can
  74. only be used with the imported target. Use of both the imported target
  75. as well as this switch is highly recommended for new code.
  76. This variable has no effect if the system libraries provide the
  77. thread functions, i.e. when ``CMAKE_THREAD_LIBS_INIT`` will be empty.
  78. Examples
  79. ^^^^^^^^
  80. Finding Threads and linking the imported target to a project target:
  81. .. code-block:: cmake
  82. set(THREADS_PREFER_PTHREAD_FLAG TRUE)
  83. find_package(Threads)
  84. target_link_libraries(example PRIVATE Threads::Threads)
  85. #]=======================================================================]
  86. include (CheckLibraryExists)
  87. set(Threads_FOUND FALSE)
  88. set(CMAKE_REQUIRED_QUIET_SAVE ${CMAKE_REQUIRED_QUIET})
  89. set(CMAKE_REQUIRED_QUIET ${Threads_FIND_QUIETLY})
  90. if(CMAKE_C_COMPILER_LOADED)
  91. include (CheckIncludeFile)
  92. include (CheckCSourceCompiles)
  93. elseif(CMAKE_CXX_COMPILER_LOADED)
  94. include (CheckIncludeFileCXX)
  95. include (CheckCXXSourceCompiles)
  96. else()
  97. message(FATAL_ERROR "FindThreads only works if either C or CXX language is enabled")
  98. endif()
  99. # simple pthread test code
  100. set(PTHREAD_C_CXX_TEST_SOURCE [====[
  101. #include <pthread.h>
  102. static void* test_func(void* data)
  103. {
  104. return data;
  105. }
  106. int main(void)
  107. {
  108. pthread_t thread;
  109. pthread_create(&thread, NULL, test_func, NULL);
  110. pthread_detach(thread);
  111. pthread_cancel(thread);
  112. pthread_join(thread, NULL);
  113. pthread_atfork(NULL, NULL, NULL);
  114. pthread_exit(NULL);
  115. return 0;
  116. }
  117. ]====])
  118. # Internal helper macro.
  119. # Do NOT even think about using it outside of this file!
  120. macro(_threads_check_libc)
  121. if(NOT Threads_FOUND)
  122. if(CMAKE_C_COMPILER_LOADED)
  123. check_c_source_compiles("${PTHREAD_C_CXX_TEST_SOURCE}" CMAKE_HAVE_LIBC_PTHREAD)
  124. elseif(CMAKE_CXX_COMPILER_LOADED)
  125. check_cxx_source_compiles("${PTHREAD_C_CXX_TEST_SOURCE}" CMAKE_HAVE_LIBC_PTHREAD)
  126. endif()
  127. if(CMAKE_HAVE_LIBC_PTHREAD)
  128. set(CMAKE_THREAD_LIBS_INIT "")
  129. set(Threads_FOUND TRUE)
  130. endif()
  131. endif ()
  132. endmacro()
  133. # Internal helper macro.
  134. # Do NOT even think about using it outside of this file!
  135. macro(_threads_check_lib LIBNAME FUNCNAME VARNAME)
  136. if(NOT Threads_FOUND)
  137. check_library_exists(${LIBNAME} ${FUNCNAME} "" ${VARNAME})
  138. if(${VARNAME})
  139. set(CMAKE_THREAD_LIBS_INIT "-l${LIBNAME}")
  140. set(Threads_FOUND TRUE)
  141. endif()
  142. endif ()
  143. endmacro()
  144. # Internal helper macro.
  145. # Do NOT even think about using it outside of this file!
  146. macro(_threads_check_flag_pthread)
  147. if(NOT Threads_FOUND)
  148. # If we did not find -lpthreads, -lpthread, or -lthread, look for -pthread
  149. # except on compilers known to not have it.
  150. if(MSVC)
  151. # Compilers targeting the MSVC ABI do not have a -pthread flag.
  152. set(THREADS_HAVE_PTHREAD_ARG FALSE)
  153. elseif(NOT DEFINED THREADS_HAVE_PTHREAD_ARG)
  154. message(CHECK_START "Check if compiler accepts -pthread")
  155. if(CMAKE_C_COMPILER_LOADED)
  156. set(_threads_src CheckForPthreads.c)
  157. elseif(CMAKE_CXX_COMPILER_LOADED)
  158. set(_threads_src CheckForPthreads.cxx)
  159. endif()
  160. try_compile(THREADS_HAVE_PTHREAD_ARG
  161. SOURCE_FROM_FILE "${_threads_src}" "${CMAKE_CURRENT_LIST_DIR}/CheckForPthreads.c"
  162. CMAKE_FLAGS -DLINK_LIBRARIES:STRING=-pthread
  163. )
  164. unset(_threads_src)
  165. if(THREADS_HAVE_PTHREAD_ARG)
  166. set(Threads_FOUND TRUE)
  167. message(CHECK_PASS "yes")
  168. else()
  169. message(CHECK_FAIL "no")
  170. endif()
  171. endif()
  172. if(THREADS_HAVE_PTHREAD_ARG)
  173. set(Threads_FOUND TRUE)
  174. set(CMAKE_THREAD_LIBS_INIT "-pthread")
  175. endif()
  176. endif()
  177. endmacro()
  178. # Check if pthread functions are in normal C library.
  179. # We list some pthread functions in PTHREAD_C_CXX_TEST_SOURCE test code.
  180. # If the pthread functions already exist in C library, we could just use
  181. # them instead of linking to the additional pthread library.
  182. _threads_check_libc()
  183. # Check for -pthread first if enabled. This is the recommended
  184. # way, but not backwards compatible as one must also pass -pthread
  185. # as compiler flag then.
  186. if (THREADS_PREFER_PTHREAD_FLAG)
  187. _threads_check_flag_pthread()
  188. endif ()
  189. if(CMAKE_SYSTEM MATCHES "GHS-MULTI")
  190. _threads_check_lib(posix pthread_create CMAKE_HAVE_PTHREADS_CREATE)
  191. endif()
  192. _threads_check_lib(pthreads pthread_create CMAKE_HAVE_PTHREADS_CREATE)
  193. _threads_check_lib(pthread pthread_create CMAKE_HAVE_PTHREAD_CREATE)
  194. if (NOT THREADS_PREFER_PTHREAD_FLAG)
  195. _threads_check_flag_pthread()
  196. endif()
  197. if(CMAKE_THREAD_LIBS_INIT OR CMAKE_HAVE_LIBC_PTHREAD)
  198. set(CMAKE_USE_PTHREADS_INIT 1)
  199. set(Threads_FOUND TRUE)
  200. endif()
  201. if(CMAKE_SYSTEM_NAME MATCHES "Windows")
  202. set(CMAKE_USE_WIN32_THREADS_INIT 1)
  203. set(Threads_FOUND TRUE)
  204. endif()
  205. if(CMAKE_USE_PTHREADS_INIT)
  206. if(CMAKE_SYSTEM_NAME MATCHES "HP-UX")
  207. # Use libcma if it exists and can be used. It provides more
  208. # symbols than the plain pthread library. CMA threads
  209. # have actually been deprecated:
  210. # http://docs.hp.com/en/B3920-90091/ch12s03.html#d0e11395
  211. # http://docs.hp.com/en/947/d8.html
  212. # but we need to maintain compatibility here.
  213. # The CMAKE_HP_PTHREADS setting actually indicates whether CMA threads
  214. # are available.
  215. check_library_exists(cma pthread_attr_create "" CMAKE_HAVE_HP_CMA)
  216. if(CMAKE_HAVE_HP_CMA)
  217. set(CMAKE_THREAD_LIBS_INIT "-lcma")
  218. set(CMAKE_HP_PTHREADS_INIT 1)
  219. set(Threads_FOUND TRUE)
  220. endif()
  221. set(CMAKE_USE_PTHREADS_INIT 1)
  222. endif()
  223. if(CMAKE_SYSTEM MATCHES "OSF1-V")
  224. set(CMAKE_USE_PTHREADS_INIT 0)
  225. set(CMAKE_THREAD_LIBS_INIT )
  226. endif()
  227. if(CMAKE_SYSTEM MATCHES "CYGWIN_NT" OR CMAKE_SYSTEM MATCHES "MSYS_NT")
  228. set(CMAKE_USE_PTHREADS_INIT 1)
  229. set(Threads_FOUND TRUE)
  230. set(CMAKE_THREAD_LIBS_INIT )
  231. set(CMAKE_USE_WIN32_THREADS_INIT 0)
  232. endif()
  233. endif()
  234. set(CMAKE_REQUIRED_QUIET ${CMAKE_REQUIRED_QUIET_SAVE})
  235. include(FindPackageHandleStandardArgs)
  236. find_package_handle_standard_args(Threads DEFAULT_MSG Threads_FOUND)
  237. if(Threads_FOUND AND NOT TARGET Threads::Threads)
  238. add_library(Threads::Threads INTERFACE IMPORTED)
  239. if(THREADS_HAVE_PTHREAD_ARG)
  240. set_property(TARGET Threads::Threads
  241. PROPERTY INTERFACE_COMPILE_OPTIONS "$<$<COMPILE_LANG_AND_ID:CUDA,NVIDIA>:SHELL:-Xcompiler -pthread>"
  242. "$<$<AND:$<NOT:$<COMPILE_LANG_AND_ID:CUDA,NVIDIA>>,$<NOT:$<COMPILE_LANGUAGE:Swift>>>:-pthread>")
  243. endif()
  244. if(CMAKE_THREAD_LIBS_INIT)
  245. set_property(TARGET Threads::Threads PROPERTY INTERFACE_LINK_LIBRARIES "${CMAKE_THREAD_LIBS_INIT}")
  246. endif()
  247. endif()