You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. // <thread> -*- C++ -*-
  2. // Copyright (C) 2008-2020 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 <bits/c++config.h>
  30. #if defined(_GLIBCXX_HAS_GTHREADS)
  31. #include <bits/gthr.h>
  32. #include <chrono> // std::chrono::*
  33. #include <memory> // std::unique_ptr
  34. #include <tuple> // std::tuple
  35. #if __cplusplus > 201703L
  36. # include <compare> // std::strong_ordering
  37. # include <stop_token> // std::stop_source, std::stop_token, std::nostopstate
  38. #endif
  39. #ifdef _GLIBCXX_USE_NANOSLEEP
  40. # include <cerrno> // errno, EINTR
  41. # include <time.h> // nanosleep
  42. #endif
  43. #include <bits/functional_hash.h> // std::hash
  44. #include <bits/invoke.h> // std::__invoke
  45. namespace std _GLIBCXX_VISIBILITY(default)
  46. {
  47. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  48. /**
  49. * @defgroup threads Threads
  50. * @ingroup concurrency
  51. *
  52. * Classes for thread support.
  53. * @{
  54. */
  55. /// thread
  56. class thread
  57. {
  58. public:
  59. // Abstract base class for types that wrap arbitrary functors to be
  60. // invoked in the new thread of execution.
  61. struct _State
  62. {
  63. virtual ~_State();
  64. virtual void _M_run() = 0;
  65. };
  66. using _State_ptr = unique_ptr<_State>;
  67. typedef __gthread_t native_handle_type;
  68. /// thread::id
  69. class id
  70. {
  71. native_handle_type _M_thread;
  72. public:
  73. id() noexcept : _M_thread() { }
  74. explicit
  75. id(native_handle_type __id) : _M_thread(__id) { }
  76. private:
  77. friend class thread;
  78. friend class hash<id>;
  79. friend bool
  80. operator==(id __x, id __y) noexcept;
  81. #if __cpp_lib_three_way_comparison
  82. friend strong_ordering
  83. operator<=>(id __x, id __y) noexcept;
  84. #else
  85. friend bool
  86. operator<(id __x, id __y) noexcept;
  87. #endif
  88. template<class _CharT, class _Traits>
  89. friend basic_ostream<_CharT, _Traits>&
  90. operator<<(basic_ostream<_CharT, _Traits>& __out, id __id);
  91. };
  92. private:
  93. id _M_id;
  94. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  95. // 2097. packaged_task constructors should be constrained
  96. // 3039. Unnecessary decay in thread and packaged_task
  97. template<typename _Tp>
  98. using __not_same = __not_<is_same<__remove_cvref_t<_Tp>, thread>>;
  99. public:
  100. thread() noexcept = default;
  101. template<typename _Callable, typename... _Args,
  102. typename = _Require<__not_same<_Callable>>>
  103. explicit
  104. thread(_Callable&& __f, _Args&&... __args)
  105. {
  106. static_assert( __is_invocable<typename decay<_Callable>::type,
  107. typename decay<_Args>::type...>::value,
  108. "std::thread arguments must be invocable after conversion to rvalues"
  109. );
  110. #ifdef GTHR_ACTIVE_PROXY
  111. // Create a reference to pthread_create, not just the gthr weak symbol.
  112. auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
  113. #else
  114. auto __depend = nullptr;
  115. #endif
  116. // A call wrapper holding tuple{DECAY_COPY(__f), DECAY_COPY(__args)...}
  117. using _Invoker_type = _Invoker<__decayed_tuple<_Callable, _Args...>>;
  118. _M_start_thread(_S_make_state<_Invoker_type>(
  119. std::forward<_Callable>(__f), std::forward<_Args>(__args)...),
  120. __depend);
  121. }
  122. ~thread()
  123. {
  124. if (joinable())
  125. std::terminate();
  126. }
  127. thread(const thread&) = delete;
  128. thread(thread&& __t) noexcept
  129. { swap(__t); }
  130. thread& operator=(const thread&) = delete;
  131. thread& operator=(thread&& __t) noexcept
  132. {
  133. if (joinable())
  134. std::terminate();
  135. swap(__t);
  136. return *this;
  137. }
  138. void
  139. swap(thread& __t) noexcept
  140. { std::swap(_M_id, __t._M_id); }
  141. bool
  142. joinable() const noexcept
  143. { return !(_M_id == id()); }
  144. void
  145. join();
  146. void
  147. detach();
  148. id
  149. get_id() const noexcept
  150. { return _M_id; }
  151. /** @pre thread is joinable
  152. */
  153. native_handle_type
  154. native_handle()
  155. { return _M_id._M_thread; }
  156. // Returns a value that hints at the number of hardware thread contexts.
  157. static unsigned int
  158. hardware_concurrency() noexcept;
  159. private:
  160. template<typename _Callable>
  161. struct _State_impl : public _State
  162. {
  163. _Callable _M_func;
  164. template<typename... _Args>
  165. _State_impl(_Args&&... __args)
  166. : _M_func{{std::forward<_Args>(__args)...}}
  167. { }
  168. void
  169. _M_run() { _M_func(); }
  170. };
  171. void
  172. _M_start_thread(_State_ptr, void (*)());
  173. template<typename _Callable, typename... _Args>
  174. static _State_ptr
  175. _S_make_state(_Args&&... __args)
  176. {
  177. using _Impl = _State_impl<_Callable>;
  178. return _State_ptr{new _Impl{std::forward<_Args>(__args)...}};
  179. }
  180. #if _GLIBCXX_THREAD_ABI_COMPAT
  181. public:
  182. struct _Impl_base;
  183. typedef shared_ptr<_Impl_base> __shared_base_type;
  184. struct _Impl_base
  185. {
  186. __shared_base_type _M_this_ptr;
  187. virtual ~_Impl_base() = default;
  188. virtual void _M_run() = 0;
  189. };
  190. private:
  191. void
  192. _M_start_thread(__shared_base_type, void (*)());
  193. void
  194. _M_start_thread(__shared_base_type);
  195. #endif
  196. private:
  197. // A call wrapper that does INVOKE(forwarded tuple elements...)
  198. template<typename _Tuple>
  199. struct _Invoker
  200. {
  201. _Tuple _M_t;
  202. template<typename>
  203. struct __result;
  204. template<typename _Fn, typename... _Args>
  205. struct __result<tuple<_Fn, _Args...>>
  206. : __invoke_result<_Fn, _Args...>
  207. { };
  208. template<size_t... _Ind>
  209. typename __result<_Tuple>::type
  210. _M_invoke(_Index_tuple<_Ind...>)
  211. { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
  212. typename __result<_Tuple>::type
  213. operator()()
  214. {
  215. using _Indices
  216. = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
  217. return _M_invoke(_Indices());
  218. }
  219. };
  220. template<typename... _Tp>
  221. using __decayed_tuple = tuple<typename decay<_Tp>::type...>;
  222. public:
  223. // Returns a call wrapper that stores
  224. // tuple{DECAY_COPY(__callable), DECAY_COPY(__args)...}.
  225. template<typename _Callable, typename... _Args>
  226. static _Invoker<__decayed_tuple<_Callable, _Args...>>
  227. __make_invoker(_Callable&& __callable, _Args&&... __args)
  228. {
  229. return { __decayed_tuple<_Callable, _Args...>{
  230. std::forward<_Callable>(__callable), std::forward<_Args>(__args)...
  231. } };
  232. }
  233. };
  234. inline void
  235. swap(thread& __x, thread& __y) noexcept
  236. { __x.swap(__y); }
  237. inline bool
  238. operator==(thread::id __x, thread::id __y) noexcept
  239. {
  240. // pthread_equal is undefined if either thread ID is not valid, so we
  241. // can't safely use __gthread_equal on default-constructed values (nor
  242. // the non-zero value returned by this_thread::get_id() for
  243. // single-threaded programs using GNU libc). Assume EqualityComparable.
  244. return __x._M_thread == __y._M_thread;
  245. }
  246. #if __cpp_lib_three_way_comparison
  247. inline strong_ordering
  248. operator<=>(thread::id __x, thread::id __y) noexcept
  249. { return __x._M_thread <=> __y._M_thread; }
  250. #else
  251. inline bool
  252. operator!=(thread::id __x, thread::id __y) noexcept
  253. { return !(__x == __y); }
  254. inline bool
  255. operator<(thread::id __x, thread::id __y) noexcept
  256. {
  257. // Pthreads doesn't define any way to do this, so we just have to
  258. // assume native_handle_type is LessThanComparable.
  259. return __x._M_thread < __y._M_thread;
  260. }
  261. inline bool
  262. operator<=(thread::id __x, thread::id __y) noexcept
  263. { return !(__y < __x); }
  264. inline bool
  265. operator>(thread::id __x, thread::id __y) noexcept
  266. { return __y < __x; }
  267. inline bool
  268. operator>=(thread::id __x, thread::id __y) noexcept
  269. { return !(__x < __y); }
  270. #endif // __cpp_lib_three_way_comparison
  271. // DR 889.
  272. /// std::hash specialization for thread::id.
  273. template<>
  274. struct hash<thread::id>
  275. : public __hash_base<size_t, thread::id>
  276. {
  277. size_t
  278. operator()(const thread::id& __id) const noexcept
  279. { return std::_Hash_impl::hash(__id._M_thread); }
  280. };
  281. template<class _CharT, class _Traits>
  282. inline basic_ostream<_CharT, _Traits>&
  283. operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
  284. {
  285. if (__id == thread::id())
  286. return __out << "thread::id of a non-executing thread";
  287. else
  288. return __out << __id._M_thread;
  289. }
  290. /** @namespace std::this_thread
  291. * @brief ISO C++ 2011 namespace for interacting with the current thread
  292. *
  293. * C++11 30.3.2 [thread.thread.this] Namespace this_thread.
  294. */
  295. namespace this_thread
  296. {
  297. /// get_id
  298. inline thread::id
  299. get_id() noexcept
  300. {
  301. #ifdef __GLIBC__
  302. // For the GNU C library pthread_self() is usable without linking to
  303. // libpthread.so but returns 0, so we cannot use it in single-threaded
  304. // programs, because this_thread::get_id() != thread::id{} must be true.
  305. // We know that pthread_t is an integral type in the GNU C library.
  306. if (!__gthread_active_p())
  307. return thread::id(1);
  308. #endif
  309. return thread::id(__gthread_self());
  310. }
  311. /// yield
  312. inline void
  313. yield() noexcept
  314. {
  315. #ifdef _GLIBCXX_USE_SCHED_YIELD
  316. __gthread_yield();
  317. #endif
  318. }
  319. void
  320. __sleep_for(chrono::seconds, chrono::nanoseconds);
  321. /// sleep_for
  322. template<typename _Rep, typename _Period>
  323. inline void
  324. sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
  325. {
  326. if (__rtime <= __rtime.zero())
  327. return;
  328. auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
  329. auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
  330. #ifdef _GLIBCXX_USE_NANOSLEEP
  331. __gthread_time_t __ts =
  332. {
  333. static_cast<std::time_t>(__s.count()),
  334. static_cast<long>(__ns.count())
  335. };
  336. while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
  337. { }
  338. #else
  339. __sleep_for(__s, __ns);
  340. #endif
  341. }
  342. /// sleep_until
  343. template<typename _Clock, typename _Duration>
  344. inline void
  345. sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
  346. {
  347. #if __cplusplus > 201703L
  348. static_assert(chrono::is_clock_v<_Clock>);
  349. #endif
  350. auto __now = _Clock::now();
  351. if (_Clock::is_steady)
  352. {
  353. if (__now < __atime)
  354. sleep_for(__atime - __now);
  355. return;
  356. }
  357. while (__now < __atime)
  358. {
  359. sleep_for(__atime - __now);
  360. __now = _Clock::now();
  361. }
  362. }
  363. }
  364. // @} group threads
  365. #ifdef __cpp_lib_jthread
  366. class jthread
  367. {
  368. public:
  369. using id = thread::id;
  370. using native_handle_type = thread::native_handle_type;
  371. jthread() noexcept
  372. : _M_stop_source{nostopstate}
  373. { }
  374. template<typename _Callable, typename... _Args,
  375. typename = enable_if_t<!is_same_v<remove_cvref_t<_Callable>,
  376. jthread>>>
  377. explicit
  378. jthread(_Callable&& __f, _Args&&... __args)
  379. : _M_thread{_S_create(_M_stop_source, std::forward<_Callable>(__f),
  380. std::forward<_Args>(__args)...)}
  381. { }
  382. jthread(const jthread&) = delete;
  383. jthread(jthread&&) noexcept = default;
  384. ~jthread()
  385. {
  386. if (joinable())
  387. {
  388. request_stop();
  389. join();
  390. }
  391. }
  392. jthread&
  393. operator=(const jthread&) = delete;
  394. jthread&
  395. operator=(jthread&&) noexcept = default;
  396. void
  397. swap(jthread& __other) noexcept
  398. {
  399. std::swap(_M_stop_source, __other._M_stop_source);
  400. std::swap(_M_thread, __other._M_thread);
  401. }
  402. [[nodiscard]] bool
  403. joinable() const noexcept
  404. {
  405. return _M_thread.joinable();
  406. }
  407. void
  408. join()
  409. {
  410. _M_thread.join();
  411. }
  412. void
  413. detach()
  414. {
  415. _M_thread.detach();
  416. }
  417. [[nodiscard]] id
  418. get_id() const noexcept
  419. {
  420. return _M_thread.get_id();
  421. }
  422. [[nodiscard]] native_handle_type
  423. native_handle()
  424. {
  425. return _M_thread.native_handle();
  426. }
  427. [[nodiscard]] static unsigned
  428. hardware_concurrency() noexcept
  429. {
  430. return thread::hardware_concurrency();
  431. }
  432. [[nodiscard]] stop_source
  433. get_stop_source() noexcept
  434. {
  435. return _M_stop_source;
  436. }
  437. [[nodiscard]] stop_token
  438. get_stop_token() const noexcept
  439. {
  440. return _M_stop_source.get_token();
  441. }
  442. bool request_stop() noexcept
  443. {
  444. return _M_stop_source.request_stop();
  445. }
  446. friend void swap(jthread& __lhs, jthread& __rhs) noexcept
  447. {
  448. __lhs.swap(__rhs);
  449. }
  450. private:
  451. template<typename _Callable, typename... _Args>
  452. static thread
  453. _S_create(stop_source& __ssrc, _Callable&& __f, _Args&&... __args)
  454. {
  455. if constexpr(is_invocable_v<decay_t<_Callable>, stop_token,
  456. decay_t<_Args>...>)
  457. return thread{std::forward<_Callable>(__f), __ssrc.get_token(),
  458. std::forward<_Args>(__args)...};
  459. else
  460. {
  461. static_assert(is_invocable_v<decay_t<_Callable>,
  462. decay_t<_Args>...>,
  463. "std::thread arguments must be invocable after"
  464. " conversion to rvalues");
  465. return thread{std::forward<_Callable>(__f),
  466. std::forward<_Args>(__args)...};
  467. }
  468. }
  469. stop_source _M_stop_source;
  470. thread _M_thread;
  471. };
  472. #endif // __cpp_lib_jthread
  473. _GLIBCXX_END_NAMESPACE_VERSION
  474. } // namespace
  475. #endif // _GLIBCXX_HAS_GTHREADS
  476. #endif // C++11
  477. #endif // _GLIBCXX_THREAD