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