thread 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. // -*- C++ -*-
  2. //===--------------------------- thread -----------------------------------===//
  3. //
  4. // The LLVM Compiler Infrastructure
  5. //
  6. // This file is dual licensed under the MIT and the University of Illinois Open
  7. // Source Licenses. See LICENSE.TXT for details.
  8. //
  9. //===----------------------------------------------------------------------===//
  10. #ifndef _LIBCPP_THREAD
  11. #define _LIBCPP_THREAD
  12. /*
  13. thread synopsis
  14. #define __STDCPP_THREADS__ __cplusplus
  15. namespace std
  16. {
  17. class thread
  18. {
  19. public:
  20. class id;
  21. typedef pthread_t native_handle_type;
  22. thread() noexcept;
  23. template <class F, class ...Args> explicit thread(F&& f, Args&&... args);
  24. ~thread();
  25. thread(const thread&) = delete;
  26. thread(thread&& t) noexcept;
  27. thread& operator=(const thread&) = delete;
  28. thread& operator=(thread&& t) noexcept;
  29. void swap(thread& t) noexcept;
  30. bool joinable() const noexcept;
  31. void join();
  32. void detach();
  33. id get_id() const noexcept;
  34. native_handle_type native_handle();
  35. static unsigned hardware_concurrency() noexcept;
  36. };
  37. void swap(thread& x, thread& y) noexcept;
  38. class thread::id
  39. {
  40. public:
  41. id() noexcept;
  42. };
  43. bool operator==(thread::id x, thread::id y) noexcept;
  44. bool operator!=(thread::id x, thread::id y) noexcept;
  45. bool operator< (thread::id x, thread::id y) noexcept;
  46. bool operator<=(thread::id x, thread::id y) noexcept;
  47. bool operator> (thread::id x, thread::id y) noexcept;
  48. bool operator>=(thread::id x, thread::id y) noexcept;
  49. template<class charT, class traits>
  50. basic_ostream<charT, traits>&
  51. operator<<(basic_ostream<charT, traits>& out, thread::id id);
  52. namespace this_thread
  53. {
  54. thread::id get_id() noexcept;
  55. void yield() noexcept;
  56. template <class Clock, class Duration>
  57. void sleep_until(const chrono::time_point<Clock, Duration>& abs_time);
  58. template <class Rep, class Period>
  59. void sleep_for(const chrono::duration<Rep, Period>& rel_time);
  60. } // this_thread
  61. } // std
  62. */
  63. // Not supported in SGX.
  64. #include <__config>
  65. #if !defined(_LIBCPP_SGX_CONFIG)
  66. #include <iosfwd>
  67. #include <__functional_base>
  68. #include <type_traits>
  69. #include <cstddef>
  70. #include <functional>
  71. #include <memory>
  72. #include <system_error>
  73. #include <chrono>
  74. #include <__mutex_base>
  75. #ifndef _LIBCPP_HAS_NO_VARIADICS
  76. #include <tuple>
  77. #endif
  78. #include <__threading_support>
  79. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  80. #pragma GCC system_header
  81. #endif
  82. #define __STDCPP_THREADS__ __cplusplus
  83. #ifdef _LIBCPP_HAS_NO_THREADS
  84. #error <thread> is not supported on this single threaded system
  85. #else // !_LIBCPP_HAS_NO_THREADS
  86. _LIBCPP_BEGIN_NAMESPACE_STD
  87. template <class _Tp> class __thread_specific_ptr;
  88. class _LIBCPP_TYPE_VIS __thread_struct;
  89. class _LIBCPP_HIDDEN __thread_struct_imp;
  90. class __assoc_sub_state;
  91. _LIBCPP_FUNC_VIS __thread_specific_ptr<__thread_struct>& __thread_local_data();
  92. class _LIBCPP_TYPE_VIS __thread_struct
  93. {
  94. __thread_struct_imp* __p_;
  95. __thread_struct(const __thread_struct&);
  96. __thread_struct& operator=(const __thread_struct&);
  97. public:
  98. __thread_struct();
  99. ~__thread_struct();
  100. void notify_all_at_thread_exit(condition_variable*, mutex*);
  101. void __make_ready_at_thread_exit(__assoc_sub_state*);
  102. };
  103. template <class _Tp>
  104. class __thread_specific_ptr
  105. {
  106. __libcpp_tl_key __key_;
  107. // Only __thread_local_data() may construct a __thread_specific_ptr
  108. // and only with _Tp == __thread_struct.
  109. static_assert((is_same<_Tp, __thread_struct>::value), "");
  110. __thread_specific_ptr();
  111. friend _LIBCPP_FUNC_VIS __thread_specific_ptr<__thread_struct>& __thread_local_data();
  112. __thread_specific_ptr(const __thread_specific_ptr&);
  113. __thread_specific_ptr& operator=(const __thread_specific_ptr&);
  114. static void __at_thread_exit(void*);
  115. public:
  116. typedef _Tp* pointer;
  117. ~__thread_specific_ptr();
  118. _LIBCPP_INLINE_VISIBILITY
  119. pointer get() const {return static_cast<_Tp*>(__libcpp_tl_get(__key_));}
  120. _LIBCPP_INLINE_VISIBILITY
  121. pointer operator*() const {return *get();}
  122. _LIBCPP_INLINE_VISIBILITY
  123. pointer operator->() const {return get();}
  124. pointer release();
  125. void reset(pointer __p = nullptr);
  126. };
  127. template <class _Tp>
  128. void
  129. __thread_specific_ptr<_Tp>::__at_thread_exit(void* __p)
  130. {
  131. delete static_cast<pointer>(__p);
  132. }
  133. template <class _Tp>
  134. __thread_specific_ptr<_Tp>::__thread_specific_ptr()
  135. {
  136. int __ec = __libcpp_tl_create(
  137. &__key_,
  138. &__thread_specific_ptr::__at_thread_exit);
  139. if (__ec)
  140. __throw_system_error(__ec,
  141. "__thread_specific_ptr construction failed");
  142. }
  143. template <class _Tp>
  144. __thread_specific_ptr<_Tp>::~__thread_specific_ptr()
  145. {
  146. // __thread_specific_ptr is only created with a static storage duration
  147. // so this destructor is only invoked during program termination. Invoking
  148. // pthread_key_delete(__key_) may prevent other threads from deleting their
  149. // thread local data. For this reason we leak the key.
  150. }
  151. template <class _Tp>
  152. typename __thread_specific_ptr<_Tp>::pointer
  153. __thread_specific_ptr<_Tp>::release()
  154. {
  155. pointer __p = get();
  156. __libcpp_tl_set(__key_, nullptr);
  157. return __p;
  158. }
  159. template <class _Tp>
  160. void
  161. __thread_specific_ptr<_Tp>::reset(pointer __p)
  162. {
  163. pointer __p_old = get();
  164. __libcpp_tl_set(__key_, __p);
  165. delete __p_old;
  166. }
  167. class _LIBCPP_TYPE_VIS thread;
  168. class _LIBCPP_TYPE_VIS __thread_id;
  169. namespace this_thread
  170. {
  171. _LIBCPP_INLINE_VISIBILITY __thread_id get_id() _NOEXCEPT;
  172. } // this_thread
  173. template<> struct hash<__thread_id>;
  174. class _LIBCPP_TYPE_VIS_ONLY __thread_id
  175. {
  176. // FIXME: pthread_t is a pointer on Darwin but a long on Linux.
  177. // NULL is the no-thread value on Darwin. Someone needs to check
  178. // on other platforms. We assume 0 works everywhere for now.
  179. __libcpp_thread_id __id_;
  180. public:
  181. _LIBCPP_INLINE_VISIBILITY
  182. __thread_id() _NOEXCEPT : __id_(0) {}
  183. friend _LIBCPP_INLINE_VISIBILITY
  184. bool operator==(__thread_id __x, __thread_id __y) _NOEXCEPT
  185. {return __libcpp_thread_id_equal(__x.__id_, __y.__id_);}
  186. friend _LIBCPP_INLINE_VISIBILITY
  187. bool operator!=(__thread_id __x, __thread_id __y) _NOEXCEPT
  188. {return !(__x == __y);}
  189. friend _LIBCPP_INLINE_VISIBILITY
  190. bool operator< (__thread_id __x, __thread_id __y) _NOEXCEPT
  191. {return __libcpp_thread_id_less(__x.__id_, __y.__id_);}
  192. friend _LIBCPP_INLINE_VISIBILITY
  193. bool operator<=(__thread_id __x, __thread_id __y) _NOEXCEPT
  194. {return !(__y < __x);}
  195. friend _LIBCPP_INLINE_VISIBILITY
  196. bool operator> (__thread_id __x, __thread_id __y) _NOEXCEPT
  197. {return __y < __x ;}
  198. friend _LIBCPP_INLINE_VISIBILITY
  199. bool operator>=(__thread_id __x, __thread_id __y) _NOEXCEPT
  200. {return !(__x < __y);}
  201. template<class _CharT, class _Traits>
  202. friend
  203. _LIBCPP_INLINE_VISIBILITY
  204. basic_ostream<_CharT, _Traits>&
  205. operator<<(basic_ostream<_CharT, _Traits>& __os, __thread_id __id)
  206. {return __os << __id.__id_;}
  207. private:
  208. _LIBCPP_INLINE_VISIBILITY
  209. __thread_id(__libcpp_thread_id __id) : __id_(__id) {}
  210. friend __thread_id this_thread::get_id() _NOEXCEPT;
  211. friend class _LIBCPP_TYPE_VIS thread;
  212. friend struct _LIBCPP_TYPE_VIS_ONLY hash<__thread_id>;
  213. };
  214. template<>
  215. struct _LIBCPP_TYPE_VIS_ONLY hash<__thread_id>
  216. : public unary_function<__thread_id, size_t>
  217. {
  218. _LIBCPP_INLINE_VISIBILITY
  219. size_t operator()(__thread_id __v) const
  220. {
  221. return hash<__libcpp_thread_id>()(__v.__id_);
  222. }
  223. };
  224. namespace this_thread
  225. {
  226. inline _LIBCPP_INLINE_VISIBILITY
  227. __thread_id
  228. get_id() _NOEXCEPT
  229. {
  230. return __libcpp_thread_get_current_id();
  231. }
  232. } // this_thread
  233. class _LIBCPP_TYPE_VIS thread
  234. {
  235. __libcpp_thread_t __t_;
  236. thread(const thread&);
  237. thread& operator=(const thread&);
  238. public:
  239. typedef __thread_id id;
  240. typedef __libcpp_thread_t native_handle_type;
  241. _LIBCPP_INLINE_VISIBILITY
  242. thread() _NOEXCEPT : __t_(0) {}
  243. #ifndef _LIBCPP_HAS_NO_VARIADICS
  244. template <class _Fp, class ..._Args,
  245. class = typename enable_if
  246. <
  247. !is_same<typename decay<_Fp>::type, thread>::value
  248. >::type
  249. >
  250. explicit thread(_Fp&& __f, _Args&&... __args);
  251. #else // _LIBCPP_HAS_NO_VARIADICS
  252. template <class _Fp> explicit thread(_Fp __f);
  253. #endif
  254. ~thread();
  255. #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
  256. _LIBCPP_INLINE_VISIBILITY
  257. thread(thread&& __t) _NOEXCEPT : __t_(__t.__t_) {__t.__t_ = 0;}
  258. _LIBCPP_INLINE_VISIBILITY
  259. thread& operator=(thread&& __t) _NOEXCEPT;
  260. #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
  261. _LIBCPP_INLINE_VISIBILITY
  262. void swap(thread& __t) _NOEXCEPT {_VSTD::swap(__t_, __t.__t_);}
  263. _LIBCPP_INLINE_VISIBILITY
  264. bool joinable() const _NOEXCEPT {return __t_ != 0;}
  265. void join();
  266. void detach();
  267. _LIBCPP_INLINE_VISIBILITY
  268. id get_id() const _NOEXCEPT {return __libcpp_thread_get_id(&__t_);}
  269. _LIBCPP_INLINE_VISIBILITY
  270. native_handle_type native_handle() _NOEXCEPT {return __t_;}
  271. static unsigned hardware_concurrency() _NOEXCEPT;
  272. };
  273. #ifndef _LIBCPP_HAS_NO_VARIADICS
  274. template <class _TSp, class _Fp, class ..._Args, size_t ..._Indices>
  275. inline _LIBCPP_INLINE_VISIBILITY
  276. void
  277. __thread_execute(tuple<_TSp, _Fp, _Args...>& __t, __tuple_indices<_Indices...>)
  278. {
  279. __invoke(_VSTD::move(_VSTD::get<1>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);
  280. }
  281. template <class _Fp>
  282. void* __thread_proxy(void* __vp)
  283. {
  284. // _Fp = std::tuple< unique_ptr<__thread_struct>, Functor, Args...>
  285. std::unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp));
  286. __thread_local_data().reset(_VSTD::get<0>(*__p).release());
  287. typedef typename __make_tuple_indices<tuple_size<_Fp>::value, 2>::type _Index;
  288. __thread_execute(*__p, _Index());
  289. return nullptr;
  290. }
  291. template <class _Fp, class ..._Args,
  292. class
  293. >
  294. thread::thread(_Fp&& __f, _Args&&... __args)
  295. {
  296. typedef unique_ptr<__thread_struct> _TSPtr;
  297. _TSPtr __tsp(new __thread_struct);
  298. typedef tuple<_TSPtr, typename decay<_Fp>::type, typename decay<_Args>::type...> _Gp;
  299. _VSTD::unique_ptr<_Gp> __p(
  300. new _Gp(std::move(__tsp),
  301. __decay_copy(_VSTD::forward<_Fp>(__f)),
  302. __decay_copy(_VSTD::forward<_Args>(__args))...));
  303. int __ec = __libcpp_thread_create(&__t_, &__thread_proxy<_Gp>, __p.get());
  304. if (__ec == 0)
  305. __p.release();
  306. else
  307. __throw_system_error(__ec, "thread constructor failed");
  308. }
  309. #else // _LIBCPP_HAS_NO_VARIADICS
  310. template <class _Fp>
  311. struct __thread_invoke_pair {
  312. // This type is used to pass memory for thread local storage and a functor
  313. // to a newly created thread because std::pair doesn't work with
  314. // std::unique_ptr in C++03.
  315. __thread_invoke_pair(_Fp& __f) : __tsp_(new __thread_struct), __fn_(__f) {}
  316. unique_ptr<__thread_struct> __tsp_;
  317. _Fp __fn_;
  318. };
  319. template <class _Fp>
  320. void* __thread_proxy_cxx03(void* __vp)
  321. {
  322. std::unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp));
  323. __thread_local_data().reset(__p->__tsp_.release());
  324. (__p->__fn_)();
  325. return nullptr;
  326. }
  327. template <class _Fp>
  328. thread::thread(_Fp __f)
  329. {
  330. typedef __thread_invoke_pair<_Fp> _InvokePair;
  331. typedef std::unique_ptr<_InvokePair> _PairPtr;
  332. _PairPtr __pp(new _InvokePair(__f));
  333. int __ec = __libcpp_thread_create(&__t_, &__thread_proxy_cxx03<_InvokePair>, __pp.get());
  334. if (__ec == 0)
  335. __pp.release();
  336. else
  337. __throw_system_error(__ec, "thread constructor failed");
  338. }
  339. #endif // _LIBCPP_HAS_NO_VARIADICS
  340. #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
  341. inline
  342. thread&
  343. thread::operator=(thread&& __t) _NOEXCEPT
  344. {
  345. if (__t_ != 0)
  346. terminate();
  347. __t_ = __t.__t_;
  348. __t.__t_ = 0;
  349. return *this;
  350. }
  351. #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
  352. inline _LIBCPP_INLINE_VISIBILITY
  353. void swap(thread& __x, thread& __y) _NOEXCEPT {__x.swap(__y);}
  354. namespace this_thread
  355. {
  356. _LIBCPP_FUNC_VIS void sleep_for(const chrono::nanoseconds& ns);
  357. template <class _Rep, class _Period>
  358. void
  359. sleep_for(const chrono::duration<_Rep, _Period>& __d)
  360. {
  361. using namespace chrono;
  362. if (__d > duration<_Rep, _Period>::zero())
  363. {
  364. _LIBCPP_CONSTEXPR duration<long double> _Max = nanoseconds::max();
  365. nanoseconds __ns;
  366. if (__d < _Max)
  367. {
  368. __ns = duration_cast<nanoseconds>(__d);
  369. if (__ns < __d)
  370. ++__ns;
  371. }
  372. else
  373. __ns = nanoseconds::max();
  374. sleep_for(__ns);
  375. }
  376. }
  377. template <class _Clock, class _Duration>
  378. void
  379. sleep_until(const chrono::time_point<_Clock, _Duration>& __t)
  380. {
  381. using namespace chrono;
  382. mutex __mut;
  383. condition_variable __cv;
  384. unique_lock<mutex> __lk(__mut);
  385. while (_Clock::now() < __t)
  386. __cv.wait_until(__lk, __t);
  387. }
  388. template <class _Duration>
  389. inline _LIBCPP_INLINE_VISIBILITY
  390. void
  391. sleep_until(const chrono::time_point<chrono::steady_clock, _Duration>& __t)
  392. {
  393. using namespace chrono;
  394. sleep_for(__t - steady_clock::now());
  395. }
  396. inline _LIBCPP_INLINE_VISIBILITY
  397. void yield() _NOEXCEPT {__libcpp_thread_yield();}
  398. } // this_thread
  399. _LIBCPP_END_NAMESPACE_STD
  400. #endif // !_LIBCPP_HAS_NO_THREADS
  401. #endif // !defined(_LIBCPP_SGX_CONFIG)
  402. #endif // _LIBCPP_THREAD