libstdc++
thread
Go to the documentation of this file.
00001 // <thread> -*- C++ -*-
00002 
00003 // Copyright (C) 2008-2018 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) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
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     template<typename _Tp>
00108       using __not_same = __not_<is_same<
00109         typename remove_cv<typename remove_reference<_Tp>::type>::type,
00110         thread>>;
00111 
00112   public:
00113     thread() noexcept = default;
00114 
00115     template<typename _Callable, typename... _Args,
00116              typename = _Require<__not_same<_Callable>>>
00117       explicit
00118       thread(_Callable&& __f, _Args&&... __args)
00119       {
00120         static_assert( __is_invocable<typename decay<_Callable>::type,
00121                                       typename decay<_Args>::type...>::value,
00122           "std::thread arguments must be invocable after conversion to rvalues"
00123           );
00124 
00125 #ifdef GTHR_ACTIVE_PROXY
00126         // Create a reference to pthread_create, not just the gthr weak symbol.
00127         auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
00128 #else
00129         auto __depend = nullptr;
00130 #endif
00131         _M_start_thread(_S_make_state(
00132               __make_invoker(std::forward<_Callable>(__f),
00133                              std::forward<_Args>(__args)...)),
00134             __depend);
00135       }
00136 
00137     ~thread()
00138     {
00139       if (joinable())
00140         std::terminate();
00141     }
00142 
00143     thread(const thread&) = delete;
00144 
00145     thread(thread&& __t) noexcept
00146     { swap(__t); }
00147 
00148     thread& operator=(const thread&) = delete;
00149 
00150     thread& operator=(thread&& __t) noexcept
00151     {
00152       if (joinable())
00153         std::terminate();
00154       swap(__t);
00155       return *this;
00156     }
00157 
00158     void
00159     swap(thread& __t) noexcept
00160     { std::swap(_M_id, __t._M_id); }
00161 
00162     bool
00163     joinable() const noexcept
00164     { return !(_M_id == id()); }
00165 
00166     void
00167     join();
00168 
00169     void
00170     detach();
00171 
00172     thread::id
00173     get_id() const noexcept
00174     { return _M_id; }
00175 
00176     /** @pre thread is joinable
00177      */
00178     native_handle_type
00179     native_handle()
00180     { return _M_id._M_thread; }
00181 
00182     // Returns a value that hints at the number of hardware thread contexts.
00183     static unsigned int
00184     hardware_concurrency() noexcept;
00185 
00186   private:
00187     template<typename _Callable>
00188       struct _State_impl : public _State
00189       {
00190         _Callable               _M_func;
00191 
00192         _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))
00193         { }
00194 
00195         void
00196         _M_run() { _M_func(); }
00197       };
00198 
00199     void
00200     _M_start_thread(_State_ptr, void (*)());
00201 
00202     template<typename _Callable>
00203       static _State_ptr
00204       _S_make_state(_Callable&& __f)
00205       {
00206         using _Impl = _State_impl<_Callable>;
00207         return _State_ptr{new _Impl{std::forward<_Callable>(__f)}};
00208       }
00209 #if _GLIBCXX_THREAD_ABI_COMPAT
00210   public:
00211     struct _Impl_base;
00212     typedef shared_ptr<_Impl_base>      __shared_base_type;
00213     struct _Impl_base
00214     {
00215       __shared_base_type        _M_this_ptr;
00216       virtual ~_Impl_base() = default;
00217       virtual void _M_run() = 0;
00218     };
00219 
00220   private:
00221     void
00222     _M_start_thread(__shared_base_type, void (*)());
00223 
00224     void
00225     _M_start_thread(__shared_base_type);
00226 #endif
00227 
00228   private:
00229     // A call wrapper that does INVOKE(forwarded tuple elements...)
00230     template<typename _Tuple>
00231       struct _Invoker
00232       {
00233         _Tuple _M_t;
00234 
00235         template<size_t _Index>
00236           static __tuple_element_t<_Index, _Tuple>&&
00237           _S_declval();
00238 
00239         template<size_t... _Ind>
00240           auto
00241           _M_invoke(_Index_tuple<_Ind...>)
00242           noexcept(noexcept(std::__invoke(_S_declval<_Ind>()...)))
00243           -> decltype(std::__invoke(_S_declval<_Ind>()...))
00244           { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
00245 
00246         using _Indices
00247           = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
00248 
00249         auto
00250         operator()()
00251         noexcept(noexcept(std::declval<_Invoker&>()._M_invoke(_Indices())))
00252         -> decltype(std::declval<_Invoker&>()._M_invoke(_Indices()))
00253         { return _M_invoke(_Indices()); }
00254       };
00255 
00256     template<typename... _Tp>
00257       using __decayed_tuple = tuple<typename std::decay<_Tp>::type...>;
00258 
00259   public:
00260     // Returns a call wrapper that stores
00261     // tuple{DECAY_COPY(__callable), DECAY_COPY(__args)...}.
00262     template<typename _Callable, typename... _Args>
00263       static _Invoker<__decayed_tuple<_Callable, _Args...>>
00264       __make_invoker(_Callable&& __callable, _Args&&... __args)
00265       {
00266         return { __decayed_tuple<_Callable, _Args...>{
00267             std::forward<_Callable>(__callable), std::forward<_Args>(__args)...
00268         } };
00269       }
00270   };
00271 
00272   inline void
00273   swap(thread& __x, thread& __y) noexcept
00274   { __x.swap(__y); }
00275 
00276   inline bool
00277   operator==(thread::id __x, thread::id __y) noexcept
00278   {
00279     // pthread_equal is undefined if either thread ID is not valid, so we
00280     // can't safely use __gthread_equal on default-constructed values (nor
00281     // the non-zero value returned by this_thread::get_id() for
00282     // single-threaded programs using GNU libc). Assume EqualityComparable.
00283     return __x._M_thread == __y._M_thread;
00284   }
00285 
00286   inline bool
00287   operator!=(thread::id __x, thread::id __y) noexcept
00288   { return !(__x == __y); }
00289 
00290   inline bool
00291   operator<(thread::id __x, thread::id __y) noexcept
00292   {
00293     // Pthreads doesn't define any way to do this, so we just have to
00294     // assume native_handle_type is LessThanComparable.
00295     return __x._M_thread < __y._M_thread;
00296   }
00297 
00298   inline bool
00299   operator<=(thread::id __x, thread::id __y) noexcept
00300   { return !(__y < __x); }
00301 
00302   inline bool
00303   operator>(thread::id __x, thread::id __y) noexcept
00304   { return __y < __x; }
00305 
00306   inline bool
00307   operator>=(thread::id __x, thread::id __y) noexcept
00308   { return !(__x < __y); }
00309 
00310   // DR 889.
00311   /// std::hash specialization for thread::id.
00312   template<>
00313     struct hash<thread::id>
00314     : public __hash_base<size_t, thread::id>
00315     {
00316       size_t
00317       operator()(const thread::id& __id) const noexcept
00318       { return std::_Hash_impl::hash(__id._M_thread); }
00319     };
00320 
00321   template<class _CharT, class _Traits>
00322     inline basic_ostream<_CharT, _Traits>&
00323     operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
00324     {
00325       if (__id == thread::id())
00326         return __out << "thread::id of a non-executing thread";
00327       else
00328         return __out << __id._M_thread;
00329     }
00330 
00331   /** @namespace std::this_thread
00332    *  @brief ISO C++ 2011 entities sub-namespace for thread.
00333    *  30.3.2 Namespace this_thread.
00334    */
00335   namespace this_thread
00336   {
00337     /// get_id
00338     inline thread::id
00339     get_id() noexcept
00340     {
00341 #ifdef __GLIBC__
00342       // For the GNU C library pthread_self() is usable without linking to
00343       // libpthread.so but returns 0, so we cannot use it in single-threaded
00344       // programs, because this_thread::get_id() != thread::id{} must be true.
00345       // We know that pthread_t is an integral type in the GNU C library.
00346       if (!__gthread_active_p())
00347         return thread::id(1);
00348 #endif
00349       return thread::id(__gthread_self());
00350     }
00351 
00352     /// yield
00353     inline void
00354     yield() noexcept
00355     {
00356 #ifdef _GLIBCXX_USE_SCHED_YIELD
00357       __gthread_yield();
00358 #endif
00359     }
00360 
00361     void
00362     __sleep_for(chrono::seconds, chrono::nanoseconds);
00363 
00364     /// sleep_for
00365     template<typename _Rep, typename _Period>
00366       inline void
00367       sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
00368       {
00369         if (__rtime <= __rtime.zero())
00370           return;
00371         auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
00372         auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
00373 #ifdef _GLIBCXX_USE_NANOSLEEP
00374         __gthread_time_t __ts =
00375           {
00376             static_cast<std::time_t>(__s.count()),
00377             static_cast<long>(__ns.count())
00378           };
00379         while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
00380           { }
00381 #else
00382         __sleep_for(__s, __ns);
00383 #endif
00384       }
00385 
00386     /// sleep_until
00387     template<typename _Clock, typename _Duration>
00388       inline void
00389       sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
00390       {
00391         auto __now = _Clock::now();
00392         if (_Clock::is_steady)
00393           {
00394             if (__now < __atime)
00395               sleep_for(__atime - __now);
00396             return;
00397           }
00398         while (__now < __atime)
00399           {
00400             sleep_for(__atime - __now);
00401             __now = _Clock::now();
00402           }
00403       }
00404   }
00405 
00406   // @} group threads
00407 
00408 _GLIBCXX_END_NAMESPACE_VERSION
00409 } // namespace
00410 
00411 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
00412 
00413 #endif // C++11
00414 
00415 #endif // _GLIBCXX_THREAD