libstdc++
|
00001 // <thread> -*- C++ -*- 00002 00003 // Copyright (C) 2008-2019 Free Software Foundation, Inc. 00004 // 00005 // This file is part of the GNU ISO C++ Library. This library is free 00006 // software; you can redistribute it and/or modify it under the 00007 // terms of the GNU General Public License as published by the 00008 // Free Software Foundation; either version 3, or (at your option) 00009 // any later version. 00010 00011 // This library is distributed in the hope that it will be useful, 00012 // but WITHOUT ANY WARRANTY; without even the implied warranty of 00013 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00014 // GNU General Public License for more details. 00015 00016 // Under Section 7 of GPL version 3, you are granted additional 00017 // permissions described in the GCC Runtime Library Exception, version 00018 // 3.1, as published by the Free Software Foundation. 00019 00020 // You should have received a copy of the GNU General Public License and 00021 // a copy of the GCC Runtime Library Exception along with this program; 00022 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see 00023 // <http://www.gnu.org/licenses/>. 00024 00025 /** @file include/thread 00026 * This is a Standard C++ Library header. 00027 */ 00028 00029 #ifndef _GLIBCXX_THREAD 00030 #define _GLIBCXX_THREAD 1 00031 00032 #pragma GCC system_header 00033 00034 #if __cplusplus < 201103L 00035 # include <bits/c++0x_warning.h> 00036 #else 00037 00038 #include <chrono> 00039 #include <memory> 00040 #include <tuple> 00041 #include <cerrno> 00042 #include <bits/functexcept.h> 00043 #include <bits/functional_hash.h> 00044 #include <bits/invoke.h> 00045 #include <bits/gthr.h> 00046 00047 #if defined(_GLIBCXX_HAS_GTHREADS) 00048 00049 namespace std _GLIBCXX_VISIBILITY(default) 00050 { 00051 _GLIBCXX_BEGIN_NAMESPACE_VERSION 00052 00053 /** 00054 * @defgroup threads Threads 00055 * @ingroup concurrency 00056 * 00057 * Classes for thread support. 00058 * @{ 00059 */ 00060 00061 /// thread 00062 class thread 00063 { 00064 public: 00065 // Abstract base class for types that wrap arbitrary functors to be 00066 // invoked in the new thread of execution. 00067 struct _State 00068 { 00069 virtual ~_State(); 00070 virtual void _M_run() = 0; 00071 }; 00072 using _State_ptr = unique_ptr<_State>; 00073 00074 typedef __gthread_t native_handle_type; 00075 00076 /// thread::id 00077 class id 00078 { 00079 native_handle_type _M_thread; 00080 00081 public: 00082 id() noexcept : _M_thread() { } 00083 00084 explicit 00085 id(native_handle_type __id) : _M_thread(__id) { } 00086 00087 private: 00088 friend class thread; 00089 friend class hash<thread::id>; 00090 00091 friend bool 00092 operator==(thread::id __x, thread::id __y) noexcept; 00093 00094 friend bool 00095 operator<(thread::id __x, thread::id __y) noexcept; 00096 00097 template<class _CharT, class _Traits> 00098 friend basic_ostream<_CharT, _Traits>& 00099 operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id); 00100 }; 00101 00102 private: 00103 id _M_id; 00104 00105 // _GLIBCXX_RESOLVE_LIB_DEFECTS 00106 // 2097. packaged_task constructors should be constrained 00107 // 3039. Unnecessary decay in thread and packaged_task 00108 template<typename _Tp> 00109 using __not_same = __not_<is_same<__remove_cvref_t<_Tp>, thread>>; 00110 00111 public: 00112 thread() noexcept = default; 00113 00114 template<typename _Callable, typename... _Args, 00115 typename = _Require<__not_same<_Callable>>> 00116 explicit 00117 thread(_Callable&& __f, _Args&&... __args) 00118 { 00119 static_assert( __is_invocable<typename decay<_Callable>::type, 00120 typename decay<_Args>::type...>::value, 00121 "std::thread arguments must be invocable after conversion to rvalues" 00122 ); 00123 00124 #ifdef GTHR_ACTIVE_PROXY 00125 // Create a reference to pthread_create, not just the gthr weak symbol. 00126 auto __depend = reinterpret_cast<void(*)()>(&pthread_create); 00127 #else 00128 auto __depend = nullptr; 00129 #endif 00130 _M_start_thread(_S_make_state( 00131 __make_invoker(std::forward<_Callable>(__f), 00132 std::forward<_Args>(__args)...)), 00133 __depend); 00134 } 00135 00136 ~thread() 00137 { 00138 if (joinable()) 00139 std::terminate(); 00140 } 00141 00142 thread(const thread&) = delete; 00143 00144 thread(thread&& __t) noexcept 00145 { swap(__t); } 00146 00147 thread& operator=(const thread&) = delete; 00148 00149 thread& operator=(thread&& __t) noexcept 00150 { 00151 if (joinable()) 00152 std::terminate(); 00153 swap(__t); 00154 return *this; 00155 } 00156 00157 void 00158 swap(thread& __t) noexcept 00159 { std::swap(_M_id, __t._M_id); } 00160 00161 bool 00162 joinable() const noexcept 00163 { return !(_M_id == id()); } 00164 00165 void 00166 join(); 00167 00168 void 00169 detach(); 00170 00171 thread::id 00172 get_id() const noexcept 00173 { return _M_id; } 00174 00175 /** @pre thread is joinable 00176 */ 00177 native_handle_type 00178 native_handle() 00179 { return _M_id._M_thread; } 00180 00181 // Returns a value that hints at the number of hardware thread contexts. 00182 static unsigned int 00183 hardware_concurrency() noexcept; 00184 00185 private: 00186 template<typename _Callable> 00187 struct _State_impl : public _State 00188 { 00189 _Callable _M_func; 00190 00191 _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f)) 00192 { } 00193 00194 void 00195 _M_run() { _M_func(); } 00196 }; 00197 00198 void 00199 _M_start_thread(_State_ptr, void (*)()); 00200 00201 template<typename _Callable> 00202 static _State_ptr 00203 _S_make_state(_Callable&& __f) 00204 { 00205 using _Impl = _State_impl<_Callable>; 00206 return _State_ptr{new _Impl{std::forward<_Callable>(__f)}}; 00207 } 00208 #if _GLIBCXX_THREAD_ABI_COMPAT 00209 public: 00210 struct _Impl_base; 00211 typedef shared_ptr<_Impl_base> __shared_base_type; 00212 struct _Impl_base 00213 { 00214 __shared_base_type _M_this_ptr; 00215 virtual ~_Impl_base() = default; 00216 virtual void _M_run() = 0; 00217 }; 00218 00219 private: 00220 void 00221 _M_start_thread(__shared_base_type, void (*)()); 00222 00223 void 00224 _M_start_thread(__shared_base_type); 00225 #endif 00226 00227 private: 00228 // A call wrapper that does INVOKE(forwarded tuple elements...) 00229 template<typename _Tuple> 00230 struct _Invoker 00231 { 00232 _Tuple _M_t; 00233 00234 template<typename> 00235 struct __result; 00236 template<typename _Fn, typename... _Args> 00237 struct __result<tuple<_Fn, _Args...>> 00238 : __invoke_result<_Fn, _Args...> 00239 { }; 00240 00241 template<size_t... _Ind> 00242 typename __result<_Tuple>::type 00243 _M_invoke(_Index_tuple<_Ind...>) 00244 { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); } 00245 00246 typename __result<_Tuple>::type 00247 operator()() 00248 { 00249 using _Indices 00250 = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type; 00251 return _M_invoke(_Indices()); 00252 } 00253 }; 00254 00255 template<typename... _Tp> 00256 using __decayed_tuple = tuple<typename decay<_Tp>::type...>; 00257 00258 public: 00259 // Returns a call wrapper that stores 00260 // tuple{DECAY_COPY(__callable), DECAY_COPY(__args)...}. 00261 template<typename _Callable, typename... _Args> 00262 static _Invoker<__decayed_tuple<_Callable, _Args...>> 00263 __make_invoker(_Callable&& __callable, _Args&&... __args) 00264 { 00265 return { __decayed_tuple<_Callable, _Args...>{ 00266 std::forward<_Callable>(__callable), std::forward<_Args>(__args)... 00267 } }; 00268 } 00269 }; 00270 00271 inline void 00272 swap(thread& __x, thread& __y) noexcept 00273 { __x.swap(__y); } 00274 00275 inline bool 00276 operator==(thread::id __x, thread::id __y) noexcept 00277 { 00278 // pthread_equal is undefined if either thread ID is not valid, so we 00279 // can't safely use __gthread_equal on default-constructed values (nor 00280 // the non-zero value returned by this_thread::get_id() for 00281 // single-threaded programs using GNU libc). Assume EqualityComparable. 00282 return __x._M_thread == __y._M_thread; 00283 } 00284 00285 inline bool 00286 operator!=(thread::id __x, thread::id __y) noexcept 00287 { return !(__x == __y); } 00288 00289 inline bool 00290 operator<(thread::id __x, thread::id __y) noexcept 00291 { 00292 // Pthreads doesn't define any way to do this, so we just have to 00293 // assume native_handle_type is LessThanComparable. 00294 return __x._M_thread < __y._M_thread; 00295 } 00296 00297 inline bool 00298 operator<=(thread::id __x, thread::id __y) noexcept 00299 { return !(__y < __x); } 00300 00301 inline bool 00302 operator>(thread::id __x, thread::id __y) noexcept 00303 { return __y < __x; } 00304 00305 inline bool 00306 operator>=(thread::id __x, thread::id __y) noexcept 00307 { return !(__x < __y); } 00308 00309 // DR 889. 00310 /// std::hash specialization for thread::id. 00311 template<> 00312 struct hash<thread::id> 00313 : public __hash_base<size_t, thread::id> 00314 { 00315 size_t 00316 operator()(const thread::id& __id) const noexcept 00317 { return std::_Hash_impl::hash(__id._M_thread); } 00318 }; 00319 00320 template<class _CharT, class _Traits> 00321 inline basic_ostream<_CharT, _Traits>& 00322 operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id) 00323 { 00324 if (__id == thread::id()) 00325 return __out << "thread::id of a non-executing thread"; 00326 else 00327 return __out << __id._M_thread; 00328 } 00329 00330 /** @namespace std::this_thread 00331 * @brief ISO C++ 2011 entities sub-namespace for thread. 00332 * 30.3.2 Namespace this_thread. 00333 */ 00334 namespace this_thread 00335 { 00336 /// get_id 00337 inline thread::id 00338 get_id() noexcept 00339 { 00340 #ifdef __GLIBC__ 00341 // For the GNU C library pthread_self() is usable without linking to 00342 // libpthread.so but returns 0, so we cannot use it in single-threaded 00343 // programs, because this_thread::get_id() != thread::id{} must be true. 00344 // We know that pthread_t is an integral type in the GNU C library. 00345 if (!__gthread_active_p()) 00346 return thread::id(1); 00347 #endif 00348 return thread::id(__gthread_self()); 00349 } 00350 00351 /// yield 00352 inline void 00353 yield() noexcept 00354 { 00355 #ifdef _GLIBCXX_USE_SCHED_YIELD 00356 __gthread_yield(); 00357 #endif 00358 } 00359 00360 void 00361 __sleep_for(chrono::seconds, chrono::nanoseconds); 00362 00363 /// sleep_for 00364 template<typename _Rep, typename _Period> 00365 inline void 00366 sleep_for(const chrono::duration<_Rep, _Period>& __rtime) 00367 { 00368 if (__rtime <= __rtime.zero()) 00369 return; 00370 auto __s = chrono::duration_cast<chrono::seconds>(__rtime); 00371 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s); 00372 #ifdef _GLIBCXX_USE_NANOSLEEP 00373 __gthread_time_t __ts = 00374 { 00375 static_cast<std::time_t>(__s.count()), 00376 static_cast<long>(__ns.count()) 00377 }; 00378 while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR) 00379 { } 00380 #else 00381 __sleep_for(__s, __ns); 00382 #endif 00383 } 00384 00385 /// sleep_until 00386 template<typename _Clock, typename _Duration> 00387 inline void 00388 sleep_until(const chrono::time_point<_Clock, _Duration>& __atime) 00389 { 00390 auto __now = _Clock::now(); 00391 if (_Clock::is_steady) 00392 { 00393 if (__now < __atime) 00394 sleep_for(__atime - __now); 00395 return; 00396 } 00397 while (__now < __atime) 00398 { 00399 sleep_for(__atime - __now); 00400 __now = _Clock::now(); 00401 } 00402 } 00403 } 00404 00405 // @} group threads 00406 00407 _GLIBCXX_END_NAMESPACE_VERSION 00408 } // namespace 00409 00410 #endif // _GLIBCXX_HAS_GTHREADS 00411 00412 #endif // C++11 00413 00414 #endif // _GLIBCXX_THREAD