thread 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. // <thread> -*- C++ -*-
  2. // Copyright (C) 2008-2018 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) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
  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. template<typename _Tp>
  85. using __not_same = __not_<is_same<
  86. typename remove_cv<typename remove_reference<_Tp>::type>::type,
  87. thread>>;
  88. public:
  89. thread() noexcept = default;
  90. template<typename _Callable, typename... _Args,
  91. typename = _Require<__not_same<_Callable>>>
  92. explicit
  93. thread(_Callable&& __f, _Args&&... __args)
  94. {
  95. static_assert( __is_invocable<typename decay<_Callable>::type,
  96. typename decay<_Args>::type...>::value,
  97. "std::thread arguments must be invocable after conversion to rvalues"
  98. );
  99. #ifdef GTHR_ACTIVE_PROXY
  100. // Create a reference to pthread_create, not just the gthr weak symbol.
  101. auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
  102. #else
  103. auto __depend = nullptr;
  104. #endif
  105. _M_start_thread(_S_make_state(
  106. __make_invoker(std::forward<_Callable>(__f),
  107. std::forward<_Args>(__args)...)),
  108. __depend);
  109. }
  110. ~thread()
  111. {
  112. if (joinable())
  113. std::terminate();
  114. }
  115. thread(const thread&) = delete;
  116. thread(thread&& __t) noexcept
  117. { swap(__t); }
  118. thread& operator=(const thread&) = delete;
  119. thread& operator=(thread&& __t) noexcept
  120. {
  121. if (joinable())
  122. std::terminate();
  123. swap(__t);
  124. return *this;
  125. }
  126. void
  127. swap(thread& __t) noexcept
  128. { std::swap(_M_id, __t._M_id); }
  129. bool
  130. joinable() const noexcept
  131. { return !(_M_id == id()); }
  132. void
  133. join();
  134. void
  135. detach();
  136. thread::id
  137. get_id() const noexcept
  138. { return _M_id; }
  139. /** @pre thread is joinable
  140. */
  141. native_handle_type
  142. native_handle()
  143. { return _M_id._M_thread; }
  144. // Returns a value that hints at the number of hardware thread contexts.
  145. static unsigned int
  146. hardware_concurrency() noexcept;
  147. private:
  148. template<typename _Callable>
  149. struct _State_impl : public _State
  150. {
  151. _Callable _M_func;
  152. _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))
  153. { }
  154. void
  155. _M_run() { _M_func(); }
  156. };
  157. void
  158. _M_start_thread(_State_ptr, void (*)());
  159. template<typename _Callable>
  160. static _State_ptr
  161. _S_make_state(_Callable&& __f)
  162. {
  163. using _Impl = _State_impl<_Callable>;
  164. return _State_ptr{new _Impl{std::forward<_Callable>(__f)}};
  165. }
  166. #if _GLIBCXX_THREAD_ABI_COMPAT
  167. public:
  168. struct _Impl_base;
  169. typedef shared_ptr<_Impl_base> __shared_base_type;
  170. struct _Impl_base
  171. {
  172. __shared_base_type _M_this_ptr;
  173. virtual ~_Impl_base() = default;
  174. virtual void _M_run() = 0;
  175. };
  176. private:
  177. void
  178. _M_start_thread(__shared_base_type, void (*)());
  179. void
  180. _M_start_thread(__shared_base_type);
  181. #endif
  182. private:
  183. // A call wrapper that does INVOKE(forwarded tuple elements...)
  184. template<typename _Tuple>
  185. struct _Invoker
  186. {
  187. _Tuple _M_t;
  188. template<size_t _Index>
  189. static __tuple_element_t<_Index, _Tuple>&&
  190. _S_declval();
  191. template<size_t... _Ind>
  192. auto
  193. _M_invoke(_Index_tuple<_Ind...>)
  194. noexcept(noexcept(std::__invoke(_S_declval<_Ind>()...)))
  195. -> decltype(std::__invoke(_S_declval<_Ind>()...))
  196. { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
  197. using _Indices
  198. = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
  199. auto
  200. operator()()
  201. noexcept(noexcept(std::declval<_Invoker&>()._M_invoke(_Indices())))
  202. -> decltype(std::declval<_Invoker&>()._M_invoke(_Indices()))
  203. { return _M_invoke(_Indices()); }
  204. };
  205. template<typename... _Tp>
  206. using __decayed_tuple = tuple<typename std::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 && _GLIBCXX_USE_C99_STDINT_TR1
  343. #endif // C++11
  344. #endif // _GLIBCXX_THREAD