thread 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. // <thread> -*- C++ -*-
  2. // Copyright (C) 2008-2019 Free Software Foundation, Inc.
  3. //
  4. // This file is part of the GNU ISO C++ Library. This library is free
  5. // software; you can redistribute it and/or modify it under the
  6. // terms of the GNU General Public License as published by the
  7. // Free Software Foundation; either version 3, or (at your option)
  8. // any later version.
  9. // This library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. // Under Section 7 of GPL version 3, you are granted additional
  14. // permissions described in the GCC Runtime Library Exception, version
  15. // 3.1, as published by the Free Software Foundation.
  16. // You should have received a copy of the GNU General Public License and
  17. // a copy of the GCC Runtime Library Exception along with this program;
  18. // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. // <http://www.gnu.org/licenses/>.
  20. /** @file include/thread
  21. * This is a Standard C++ Library header.
  22. */
  23. #ifndef _GLIBCXX_THREAD
  24. #define _GLIBCXX_THREAD 1
  25. #pragma GCC system_header
  26. #if __cplusplus < 201103L
  27. # include <bits/c++0x_warning.h>
  28. #else
  29. #include <chrono>
  30. #include <memory>
  31. #include <tuple>
  32. #include <cerrno>
  33. #include <bits/functexcept.h>
  34. #include <bits/functional_hash.h>
  35. #include <bits/invoke.h>
  36. #include <bits/gthr.h>
  37. #if defined(_GLIBCXX_HAS_GTHREADS)
  38. namespace std _GLIBCXX_VISIBILITY(default)
  39. {
  40. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  41. /**
  42. * @defgroup threads Threads
  43. * @ingroup concurrency
  44. *
  45. * Classes for thread support.
  46. * @{
  47. */
  48. /// thread
  49. class thread
  50. {
  51. public:
  52. // Abstract base class for types that wrap arbitrary functors to be
  53. // invoked in the new thread of execution.
  54. struct _State
  55. {
  56. virtual ~_State();
  57. virtual void _M_run() = 0;
  58. };
  59. using _State_ptr = unique_ptr<_State>;
  60. typedef __gthread_t native_handle_type;
  61. /// thread::id
  62. class id
  63. {
  64. native_handle_type _M_thread;
  65. public:
  66. id() noexcept : _M_thread() { }
  67. explicit
  68. id(native_handle_type __id) : _M_thread(__id) { }
  69. private:
  70. friend class thread;
  71. friend class hash<thread::id>;
  72. friend bool
  73. operator==(thread::id __x, thread::id __y) noexcept;
  74. friend bool
  75. operator<(thread::id __x, thread::id __y) noexcept;
  76. template<class _CharT, class _Traits>
  77. friend basic_ostream<_CharT, _Traits>&
  78. operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id);
  79. };
  80. private:
  81. id _M_id;
  82. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  83. // 2097. packaged_task constructors should be constrained
  84. // 3039. Unnecessary decay in thread and packaged_task
  85. template<typename _Tp>
  86. using __not_same = __not_<is_same<__remove_cvref_t<_Tp>, thread>>;
  87. public:
  88. thread() noexcept = default;
  89. template<typename _Callable, typename... _Args,
  90. typename = _Require<__not_same<_Callable>>>
  91. explicit
  92. thread(_Callable&& __f, _Args&&... __args)
  93. {
  94. static_assert( __is_invocable<typename decay<_Callable>::type,
  95. typename decay<_Args>::type...>::value,
  96. "std::thread arguments must be invocable after conversion to rvalues"
  97. );
  98. #ifdef GTHR_ACTIVE_PROXY
  99. // Create a reference to pthread_create, not just the gthr weak symbol.
  100. auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
  101. #else
  102. auto __depend = nullptr;
  103. #endif
  104. _M_start_thread(_S_make_state(
  105. __make_invoker(std::forward<_Callable>(__f),
  106. std::forward<_Args>(__args)...)),
  107. __depend);
  108. }
  109. ~thread()
  110. {
  111. if (joinable())
  112. std::terminate();
  113. }
  114. thread(const thread&) = delete;
  115. thread(thread&& __t) noexcept
  116. { swap(__t); }
  117. thread& operator=(const thread&) = delete;
  118. thread& operator=(thread&& __t) noexcept
  119. {
  120. if (joinable())
  121. std::terminate();
  122. swap(__t);
  123. return *this;
  124. }
  125. void
  126. swap(thread& __t) noexcept
  127. { std::swap(_M_id, __t._M_id); }
  128. bool
  129. joinable() const noexcept
  130. { return !(_M_id == id()); }
  131. void
  132. join();
  133. void
  134. detach();
  135. thread::id
  136. get_id() const noexcept
  137. { return _M_id; }
  138. /** @pre thread is joinable
  139. */
  140. native_handle_type
  141. native_handle()
  142. { return _M_id._M_thread; }
  143. // Returns a value that hints at the number of hardware thread contexts.
  144. static unsigned int
  145. hardware_concurrency() noexcept;
  146. private:
  147. template<typename _Callable>
  148. struct _State_impl : public _State
  149. {
  150. _Callable _M_func;
  151. _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))
  152. { }
  153. void
  154. _M_run() { _M_func(); }
  155. };
  156. void
  157. _M_start_thread(_State_ptr, void (*)());
  158. template<typename _Callable>
  159. static _State_ptr
  160. _S_make_state(_Callable&& __f)
  161. {
  162. using _Impl = _State_impl<_Callable>;
  163. return _State_ptr{new _Impl{std::forward<_Callable>(__f)}};
  164. }
  165. #if _GLIBCXX_THREAD_ABI_COMPAT
  166. public:
  167. struct _Impl_base;
  168. typedef shared_ptr<_Impl_base> __shared_base_type;
  169. struct _Impl_base
  170. {
  171. __shared_base_type _M_this_ptr;
  172. virtual ~_Impl_base() = default;
  173. virtual void _M_run() = 0;
  174. };
  175. private:
  176. void
  177. _M_start_thread(__shared_base_type, void (*)());
  178. void
  179. _M_start_thread(__shared_base_type);
  180. #endif
  181. private:
  182. // A call wrapper that does INVOKE(forwarded tuple elements...)
  183. template<typename _Tuple>
  184. struct _Invoker
  185. {
  186. _Tuple _M_t;
  187. template<typename>
  188. struct __result;
  189. template<typename _Fn, typename... _Args>
  190. struct __result<tuple<_Fn, _Args...>>
  191. : __invoke_result<_Fn, _Args...>
  192. { };
  193. template<size_t... _Ind>
  194. typename __result<_Tuple>::type
  195. _M_invoke(_Index_tuple<_Ind...>)
  196. { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
  197. typename __result<_Tuple>::type
  198. operator()()
  199. {
  200. using _Indices
  201. = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
  202. return _M_invoke(_Indices());
  203. }
  204. };
  205. template<typename... _Tp>
  206. using __decayed_tuple = tuple<typename decay<_Tp>::type...>;
  207. public:
  208. // Returns a call wrapper that stores
  209. // tuple{DECAY_COPY(__callable), DECAY_COPY(__args)...}.
  210. template<typename _Callable, typename... _Args>
  211. static _Invoker<__decayed_tuple<_Callable, _Args...>>
  212. __make_invoker(_Callable&& __callable, _Args&&... __args)
  213. {
  214. return { __decayed_tuple<_Callable, _Args...>{
  215. std::forward<_Callable>(__callable), std::forward<_Args>(__args)...
  216. } };
  217. }
  218. };
  219. inline void
  220. swap(thread& __x, thread& __y) noexcept
  221. { __x.swap(__y); }
  222. inline bool
  223. operator==(thread::id __x, thread::id __y) noexcept
  224. {
  225. // pthread_equal is undefined if either thread ID is not valid, so we
  226. // can't safely use __gthread_equal on default-constructed values (nor
  227. // the non-zero value returned by this_thread::get_id() for
  228. // single-threaded programs using GNU libc). Assume EqualityComparable.
  229. return __x._M_thread == __y._M_thread;
  230. }
  231. inline bool
  232. operator!=(thread::id __x, thread::id __y) noexcept
  233. { return !(__x == __y); }
  234. inline bool
  235. operator<(thread::id __x, thread::id __y) noexcept
  236. {
  237. // Pthreads doesn't define any way to do this, so we just have to
  238. // assume native_handle_type is LessThanComparable.
  239. return __x._M_thread < __y._M_thread;
  240. }
  241. inline bool
  242. operator<=(thread::id __x, thread::id __y) noexcept
  243. { return !(__y < __x); }
  244. inline bool
  245. operator>(thread::id __x, thread::id __y) noexcept
  246. { return __y < __x; }
  247. inline bool
  248. operator>=(thread::id __x, thread::id __y) noexcept
  249. { return !(__x < __y); }
  250. // DR 889.
  251. /// std::hash specialization for thread::id.
  252. template<>
  253. struct hash<thread::id>
  254. : public __hash_base<size_t, thread::id>
  255. {
  256. size_t
  257. operator()(const thread::id& __id) const noexcept
  258. { return std::_Hash_impl::hash(__id._M_thread); }
  259. };
  260. template<class _CharT, class _Traits>
  261. inline basic_ostream<_CharT, _Traits>&
  262. operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
  263. {
  264. if (__id == thread::id())
  265. return __out << "thread::id of a non-executing thread";
  266. else
  267. return __out << __id._M_thread;
  268. }
  269. /** @namespace std::this_thread
  270. * @brief ISO C++ 2011 entities sub-namespace for thread.
  271. * 30.3.2 Namespace this_thread.
  272. */
  273. namespace this_thread
  274. {
  275. /// get_id
  276. inline thread::id
  277. get_id() noexcept
  278. {
  279. #ifdef __GLIBC__
  280. // For the GNU C library pthread_self() is usable without linking to
  281. // libpthread.so but returns 0, so we cannot use it in single-threaded
  282. // programs, because this_thread::get_id() != thread::id{} must be true.
  283. // We know that pthread_t is an integral type in the GNU C library.
  284. if (!__gthread_active_p())
  285. return thread::id(1);
  286. #endif
  287. return thread::id(__gthread_self());
  288. }
  289. /// yield
  290. inline void
  291. yield() noexcept
  292. {
  293. #ifdef _GLIBCXX_USE_SCHED_YIELD
  294. __gthread_yield();
  295. #endif
  296. }
  297. void
  298. __sleep_for(chrono::seconds, chrono::nanoseconds);
  299. /// sleep_for
  300. template<typename _Rep, typename _Period>
  301. inline void
  302. sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
  303. {
  304. if (__rtime <= __rtime.zero())
  305. return;
  306. auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
  307. auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
  308. #ifdef _GLIBCXX_USE_NANOSLEEP
  309. __gthread_time_t __ts =
  310. {
  311. static_cast<std::time_t>(__s.count()),
  312. static_cast<long>(__ns.count())
  313. };
  314. while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
  315. { }
  316. #else
  317. __sleep_for(__s, __ns);
  318. #endif
  319. }
  320. /// sleep_until
  321. template<typename _Clock, typename _Duration>
  322. inline void
  323. sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
  324. {
  325. auto __now = _Clock::now();
  326. if (_Clock::is_steady)
  327. {
  328. if (__now < __atime)
  329. sleep_for(__atime - __now);
  330. return;
  331. }
  332. while (__now < __atime)
  333. {
  334. sleep_for(__atime - __now);
  335. __now = _Clock::now();
  336. }
  337. }
  338. }
  339. // @} group threads
  340. _GLIBCXX_END_NAMESPACE_VERSION
  341. } // namespace
  342. #endif // _GLIBCXX_HAS_GTHREADS
  343. #endif // C++11
  344. #endif // _GLIBCXX_THREAD