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     // Alias for _Invoker<tuple<DECAY_COPY(_Tp)...>>
00247     template<typename... _Tp>
00248       using __invoker_type
00249         = _Invoker<decltype(std::make_tuple(std::declval<_Tp>()...))>;
00250 
00251   public:
00252     // Returns a call wrapper that does
00253     // INVOKE(DECAY_COPY(__callable), DECAY_COPY(__args)).
00254     template<typename _Callable, typename... _Args>
00255       static __invoker_type<_Callable, _Args...>
00256       __make_invoker(_Callable&& __callable, _Args&&... __args)
00257       {
00258         return { {
00259             std::make_tuple(std::forward<_Callable>(__callable),
00260                             std::forward<_Args>(__args)...)
00261         } };
00262       }
00263   };
00264 
00265   inline void
00266   swap(thread& __x, thread& __y) noexcept
00267   { __x.swap(__y); }
00268 
00269   inline bool
00270   operator==(thread::id __x, thread::id __y) noexcept
00271   {
00272     // pthread_equal is undefined if either thread ID is not valid, so we
00273     // can't safely use __gthread_equal on default-constructed values (nor
00274     // the non-zero value returned by this_thread::get_id() for
00275     // single-threaded programs using GNU libc). Assume EqualityComparable.
00276     return __x._M_thread == __y._M_thread;
00277   }
00278 
00279   inline bool
00280   operator!=(thread::id __x, thread::id __y) noexcept
00281   { return !(__x == __y); }
00282 
00283   inline bool
00284   operator<(thread::id __x, thread::id __y) noexcept
00285   {
00286     // Pthreads doesn't define any way to do this, so we just have to
00287     // assume native_handle_type is LessThanComparable.
00288     return __x._M_thread < __y._M_thread;
00289   }
00290 
00291   inline bool
00292   operator<=(thread::id __x, thread::id __y) noexcept
00293   { return !(__y < __x); }
00294 
00295   inline bool
00296   operator>(thread::id __x, thread::id __y) noexcept
00297   { return __y < __x; }
00298 
00299   inline bool
00300   operator>=(thread::id __x, thread::id __y) noexcept
00301   { return !(__x < __y); }
00302 
00303   // DR 889.
00304   /// std::hash specialization for thread::id.
00305   template<>
00306     struct hash<thread::id>
00307     : public __hash_base<size_t, thread::id>
00308     {
00309       size_t
00310       operator()(const thread::id& __id) const noexcept
00311       { return std::_Hash_impl::hash(__id._M_thread); }
00312     };
00313 
00314   template<class _CharT, class _Traits>
00315     inline basic_ostream<_CharT, _Traits>&
00316     operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
00317     {
00318       if (__id == thread::id())
00319         return __out << "thread::id of a non-executing thread";
00320       else
00321         return __out << __id._M_thread;
00322     }
00323 
00324 _GLIBCXX_END_NAMESPACE_VERSION
00325 
00326   /** @namespace std::this_thread
00327    *  @brief ISO C++ 2011 entities sub-namespace for thread.
00328    *  30.3.2 Namespace this_thread.
00329    */
00330   namespace this_thread
00331   {
00332   _GLIBCXX_BEGIN_NAMESPACE_VERSION
00333 
00334     /// get_id
00335     inline thread::id
00336     get_id() noexcept
00337     {
00338 #ifdef __GLIBC__
00339       // For the GNU C library pthread_self() is usable without linking to
00340       // libpthread.so but returns 0, so we cannot use it in single-threaded
00341       // programs, because this_thread::get_id() != thread::id{} must be true.
00342       // We know that pthread_t is an integral type in the GNU C library.
00343       if (!__gthread_active_p())
00344         return thread::id(1);
00345 #endif
00346       return thread::id(__gthread_self());
00347     }
00348 
00349     /// yield
00350     inline void
00351     yield() noexcept
00352     {
00353 #ifdef _GLIBCXX_USE_SCHED_YIELD
00354       __gthread_yield();
00355 #endif
00356     }
00357 
00358     void
00359     __sleep_for(chrono::seconds, chrono::nanoseconds);
00360 
00361     /// sleep_for
00362     template<typename _Rep, typename _Period>
00363       inline void
00364       sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
00365       {
00366         if (__rtime <= __rtime.zero())
00367           return;
00368         auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
00369         auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
00370 #ifdef _GLIBCXX_USE_NANOSLEEP
00371         __gthread_time_t __ts =
00372           {
00373             static_cast<std::time_t>(__s.count()),
00374             static_cast<long>(__ns.count())
00375           };
00376         while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
00377           { }
00378 #else
00379         __sleep_for(__s, __ns);
00380 #endif
00381       }
00382 
00383     /// sleep_until
00384     template<typename _Clock, typename _Duration>
00385       inline void
00386       sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
00387       {
00388         auto __now = _Clock::now();
00389         if (_Clock::is_steady)
00390           {
00391             if (__now < __atime)
00392               sleep_for(__atime - __now);
00393             return;
00394           }
00395         while (__now < __atime)
00396           {
00397             sleep_for(__atime - __now);
00398             __now = _Clock::now();
00399           }
00400       }
00401 
00402   _GLIBCXX_END_NAMESPACE_VERSION
00403   }
00404 
00405   // @} group threads
00406 
00407 } // namespace
00408 
00409 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
00410 
00411 #endif // C++11
00412 
00413 #endif // _GLIBCXX_THREAD