thread 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. // <thread> -*- C++ -*-
  2. // Copyright (C) 2008-2016 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 <functional>
  31. #include <memory>
  32. #include <cerrno>
  33. #include <bits/functexcept.h>
  34. #include <bits/functional_hash.h>
  35. #include <bits/gthr.h>
  36. #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
  37. namespace std _GLIBCXX_VISIBILITY(default)
  38. {
  39. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  40. /**
  41. * @defgroup threads Threads
  42. * @ingroup concurrency
  43. *
  44. * Classes for thread support.
  45. * @{
  46. */
  47. /// thread
  48. class thread
  49. {
  50. public:
  51. // Abstract base class for types that wrap arbitrary functors to be
  52. // invoked in the new thread of execution.
  53. struct _State
  54. {
  55. virtual ~_State();
  56. virtual void _M_run() = 0;
  57. };
  58. using _State_ptr = unique_ptr<_State>;
  59. typedef __gthread_t native_handle_type;
  60. /// thread::id
  61. class id
  62. {
  63. native_handle_type _M_thread;
  64. public:
  65. id() noexcept : _M_thread() { }
  66. explicit
  67. id(native_handle_type __id) : _M_thread(__id) { }
  68. private:
  69. friend class thread;
  70. friend class hash<thread::id>;
  71. friend bool
  72. operator==(thread::id __x, thread::id __y) noexcept
  73. {
  74. // pthread_equal is undefined if either thread ID is not valid, so we
  75. // can't safely use __gthread_equal on default-constructed values (nor
  76. // the non-zero value returned by this_thread::get_id() for
  77. // single-threaded programs using GNU libc). Assume EqualityComparable.
  78. return __x._M_thread == __y._M_thread;
  79. }
  80. friend bool
  81. operator<(thread::id __x, thread::id __y) noexcept
  82. {
  83. // Pthreads doesn't define any way to do this, so we just have to
  84. // assume native_handle_type is LessThanComparable.
  85. return __x._M_thread < __y._M_thread;
  86. }
  87. template<class _CharT, class _Traits>
  88. friend basic_ostream<_CharT, _Traits>&
  89. operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id);
  90. };
  91. private:
  92. id _M_id;
  93. public:
  94. thread() noexcept = default;
  95. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  96. // 2097. packaged_task constructors should be constrained
  97. thread(thread&) = delete;
  98. thread(const thread&) = delete;
  99. thread(thread&& __t) noexcept
  100. { swap(__t); }
  101. template<typename _Callable, typename... _Args>
  102. explicit
  103. thread(_Callable&& __f, _Args&&... __args)
  104. {
  105. #ifdef GTHR_ACTIVE_PROXY
  106. // Create a reference to pthread_create, not just the gthr weak symbol.
  107. auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
  108. #else
  109. auto __depend = nullptr;
  110. #endif
  111. _M_start_thread(_S_make_state(
  112. std::__bind_simple(std::forward<_Callable>(__f),
  113. std::forward<_Args>(__args)...)),
  114. __depend);
  115. }
  116. ~thread()
  117. {
  118. if (joinable())
  119. std::terminate();
  120. }
  121. thread& operator=(const thread&) = delete;
  122. thread& operator=(thread&& __t) noexcept
  123. {
  124. if (joinable())
  125. std::terminate();
  126. swap(__t);
  127. return *this;
  128. }
  129. void
  130. swap(thread& __t) noexcept
  131. { std::swap(_M_id, __t._M_id); }
  132. bool
  133. joinable() const noexcept
  134. { return !(_M_id == id()); }
  135. void
  136. join();
  137. void
  138. detach();
  139. thread::id
  140. get_id() const noexcept
  141. { return _M_id; }
  142. /** @pre thread is joinable
  143. */
  144. native_handle_type
  145. native_handle()
  146. { return _M_id._M_thread; }
  147. // Returns a value that hints at the number of hardware thread contexts.
  148. static unsigned int
  149. hardware_concurrency() noexcept;
  150. private:
  151. template<typename _Callable>
  152. struct _State_impl : public _State
  153. {
  154. _Callable _M_func;
  155. _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))
  156. { }
  157. void
  158. _M_run() { _M_func(); }
  159. };
  160. void
  161. _M_start_thread(_State_ptr, void (*)());
  162. template<typename _Callable>
  163. static _State_ptr
  164. _S_make_state(_Callable&& __f)
  165. {
  166. using _Impl = _State_impl<_Callable>;
  167. return _State_ptr{new _Impl{std::forward<_Callable>(__f)}};
  168. }
  169. #if _GLIBCXX_THREAD_ABI_COMPAT
  170. public:
  171. struct _Impl_base;
  172. typedef shared_ptr<_Impl_base> __shared_base_type;
  173. struct _Impl_base
  174. {
  175. __shared_base_type _M_this_ptr;
  176. virtual ~_Impl_base() = default;
  177. virtual void _M_run() = 0;
  178. };
  179. private:
  180. void
  181. _M_start_thread(__shared_base_type, void (*)());
  182. void
  183. _M_start_thread(__shared_base_type);
  184. #endif
  185. };
  186. inline void
  187. swap(thread& __x, thread& __y) noexcept
  188. { __x.swap(__y); }
  189. inline bool
  190. operator!=(thread::id __x, thread::id __y) noexcept
  191. { return !(__x == __y); }
  192. inline bool
  193. operator<=(thread::id __x, thread::id __y) noexcept
  194. { return !(__y < __x); }
  195. inline bool
  196. operator>(thread::id __x, thread::id __y) noexcept
  197. { return __y < __x; }
  198. inline bool
  199. operator>=(thread::id __x, thread::id __y) noexcept
  200. { return !(__x < __y); }
  201. // DR 889.
  202. /// std::hash specialization for thread::id.
  203. template<>
  204. struct hash<thread::id>
  205. : public __hash_base<size_t, thread::id>
  206. {
  207. size_t
  208. operator()(const thread::id& __id) const noexcept
  209. { return std::_Hash_impl::hash(__id._M_thread); }
  210. };
  211. template<class _CharT, class _Traits>
  212. inline basic_ostream<_CharT, _Traits>&
  213. operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
  214. {
  215. if (__id == thread::id())
  216. return __out << "thread::id of a non-executing thread";
  217. else
  218. return __out << __id._M_thread;
  219. }
  220. _GLIBCXX_END_NAMESPACE_VERSION
  221. /** @namespace std::this_thread
  222. * @brief ISO C++ 2011 entities sub-namespace for thread.
  223. * 30.3.2 Namespace this_thread.
  224. */
  225. namespace this_thread
  226. {
  227. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  228. /// get_id
  229. inline thread::id
  230. get_id() noexcept
  231. {
  232. #ifdef __GLIBC__
  233. // For the GNU C library pthread_self() is usable without linking to
  234. // libpthread.so but returns 0, so we cannot use it in single-threaded
  235. // programs, because this_thread::get_id() != thread::id{} must be true.
  236. // We know that pthread_t is an integral type in the GNU C library.
  237. if (!__gthread_active_p())
  238. return thread::id(1);
  239. #endif
  240. return thread::id(__gthread_self());
  241. }
  242. /// yield
  243. inline void
  244. yield() noexcept
  245. {
  246. #ifdef _GLIBCXX_USE_SCHED_YIELD
  247. __gthread_yield();
  248. #endif
  249. }
  250. void
  251. __sleep_for(chrono::seconds, chrono::nanoseconds);
  252. /// sleep_for
  253. template<typename _Rep, typename _Period>
  254. inline void
  255. sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
  256. {
  257. if (__rtime <= __rtime.zero())
  258. return;
  259. auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
  260. auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
  261. #ifdef _GLIBCXX_USE_NANOSLEEP
  262. __gthread_time_t __ts =
  263. {
  264. static_cast<std::time_t>(__s.count()),
  265. static_cast<long>(__ns.count())
  266. };
  267. while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
  268. { }
  269. #else
  270. __sleep_for(__s, __ns);
  271. #endif
  272. }
  273. /// sleep_until
  274. template<typename _Clock, typename _Duration>
  275. inline void
  276. sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
  277. {
  278. auto __now = _Clock::now();
  279. if (_Clock::is_steady)
  280. {
  281. if (__now < __atime)
  282. sleep_for(__atime - __now);
  283. return;
  284. }
  285. while (__now < __atime)
  286. {
  287. sleep_for(__atime - __now);
  288. __now = _Clock::now();
  289. }
  290. }
  291. _GLIBCXX_END_NAMESPACE_VERSION
  292. }
  293. // @} group threads
  294. } // namespace
  295. #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
  296. #endif // C++11
  297. #endif // _GLIBCXX_THREAD