libstdc++
thread
Go to the documentation of this file.
00001 // <thread> -*- C++ -*-
00002 
00003 // Copyright (C) 2008-2016 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 <functional>
00040 #include <memory>
00041 #include <cerrno>
00042 #include <bits/functexcept.h>
00043 #include <bits/functional_hash.h>
00044 #include <bits/gthr.h>
00045 
00046 #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
00047 
00048 namespace std _GLIBCXX_VISIBILITY(default)
00049 {
00050 _GLIBCXX_BEGIN_NAMESPACE_VERSION
00051 
00052   /**
00053    * @defgroup threads Threads
00054    * @ingroup concurrency
00055    *
00056    * Classes for thread support.
00057    * @{
00058    */
00059 
00060   /// thread
00061   class thread
00062   {
00063   public:
00064     // Abstract base class for types that wrap arbitrary functors to be
00065     // invoked in the new thread of execution.
00066     struct _State
00067     {
00068       virtual ~_State();
00069       virtual void _M_run() = 0;
00070     };
00071     using _State_ptr = unique_ptr<_State>;
00072 
00073     typedef __gthread_t                 native_handle_type;
00074 
00075     /// thread::id
00076     class id
00077     {
00078       native_handle_type        _M_thread;
00079 
00080     public:
00081       id() noexcept : _M_thread() { }
00082 
00083       explicit
00084       id(native_handle_type __id) : _M_thread(__id) { }
00085 
00086     private:
00087       friend class thread;
00088       friend class hash<thread::id>;
00089 
00090       friend bool
00091       operator==(thread::id __x, thread::id __y) noexcept
00092       {
00093         // pthread_equal is undefined if either thread ID is not valid, so we
00094         // can't safely use __gthread_equal on default-constructed values (nor
00095         // the non-zero value returned by this_thread::get_id() for
00096         // single-threaded programs using GNU libc). Assume EqualityComparable.
00097         return __x._M_thread == __y._M_thread;
00098       }
00099 
00100       friend bool
00101       operator<(thread::id __x, thread::id __y) noexcept
00102       {
00103         // Pthreads doesn't define any way to do this, so we just have to
00104         // assume native_handle_type is LessThanComparable.
00105         return __x._M_thread < __y._M_thread;
00106       }
00107 
00108       template<class _CharT, class _Traits>
00109         friend basic_ostream<_CharT, _Traits>&
00110         operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id);
00111     };
00112 
00113   private:
00114     id                          _M_id;
00115 
00116   public:
00117     thread() noexcept = default;
00118     // _GLIBCXX_RESOLVE_LIB_DEFECTS
00119     // 2097.  packaged_task constructors should be constrained
00120     thread(thread&) = delete;
00121     thread(const thread&) = delete;
00122 
00123     thread(thread&& __t) noexcept
00124     { swap(__t); }
00125 
00126     template<typename _Callable, typename... _Args>
00127       explicit 
00128       thread(_Callable&& __f, _Args&&... __args)
00129       {
00130 #ifdef GTHR_ACTIVE_PROXY
00131         // Create a reference to pthread_create, not just the gthr weak symbol.
00132         auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
00133 #else
00134         auto __depend = nullptr;
00135 #endif
00136         _M_start_thread(_S_make_state(
00137               std::__bind_simple(std::forward<_Callable>(__f),
00138                                  std::forward<_Args>(__args)...)),
00139             __depend);
00140       }
00141 
00142     ~thread()
00143     {
00144       if (joinable())
00145         std::terminate();
00146     }
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 
00229   inline void
00230   swap(thread& __x, thread& __y) noexcept
00231   { __x.swap(__y); }
00232 
00233   inline bool
00234   operator!=(thread::id __x, thread::id __y) noexcept
00235   { return !(__x == __y); }
00236 
00237   inline bool
00238   operator<=(thread::id __x, thread::id __y) noexcept
00239   { return !(__y < __x); }
00240 
00241   inline bool
00242   operator>(thread::id __x, thread::id __y) noexcept
00243   { return __y < __x; }
00244 
00245   inline bool
00246   operator>=(thread::id __x, thread::id __y) noexcept
00247   { return !(__x < __y); }
00248 
00249   // DR 889.
00250   /// std::hash specialization for thread::id.
00251   template<>
00252     struct hash<thread::id>
00253     : public __hash_base<size_t, thread::id>
00254     {
00255       size_t
00256       operator()(const thread::id& __id) const noexcept
00257       { return std::_Hash_impl::hash(__id._M_thread); }
00258     };
00259 
00260   template<class _CharT, class _Traits>
00261     inline basic_ostream<_CharT, _Traits>&
00262     operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
00263     {
00264       if (__id == thread::id())
00265         return __out << "thread::id of a non-executing thread";
00266       else
00267         return __out << __id._M_thread;
00268     }
00269 
00270 _GLIBCXX_END_NAMESPACE_VERSION
00271 
00272   /** @namespace std::this_thread
00273    *  @brief ISO C++ 2011 entities sub-namespace for thread.
00274    *  30.3.2 Namespace this_thread.
00275    */
00276   namespace this_thread
00277   {
00278   _GLIBCXX_BEGIN_NAMESPACE_VERSION
00279 
00280     /// get_id
00281     inline thread::id
00282     get_id() noexcept
00283     {
00284 #ifdef __GLIBC__
00285       // For the GNU C library pthread_self() is usable without linking to
00286       // libpthread.so but returns 0, so we cannot use it in single-threaded
00287       // programs, because this_thread::get_id() != thread::id{} must be true.
00288       // We know that pthread_t is an integral type in the GNU C library.
00289       if (!__gthread_active_p())
00290         return thread::id(1);
00291 #endif
00292       return thread::id(__gthread_self());
00293     }
00294 
00295     /// yield
00296     inline void
00297     yield() noexcept
00298     {
00299 #ifdef _GLIBCXX_USE_SCHED_YIELD
00300       __gthread_yield();
00301 #endif
00302     }
00303 
00304     void
00305     __sleep_for(chrono::seconds, chrono::nanoseconds);
00306 
00307     /// sleep_for
00308     template<typename _Rep, typename _Period>
00309       inline void
00310       sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
00311       {
00312         if (__rtime <= __rtime.zero())
00313           return;
00314         auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
00315         auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
00316 #ifdef _GLIBCXX_USE_NANOSLEEP
00317         __gthread_time_t __ts =
00318           {
00319             static_cast<std::time_t>(__s.count()),
00320             static_cast<long>(__ns.count())
00321           };
00322         while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
00323           { }
00324 #else
00325         __sleep_for(__s, __ns);
00326 #endif
00327       }
00328 
00329     /// sleep_until
00330     template<typename _Clock, typename _Duration>
00331       inline void
00332       sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
00333       {
00334         auto __now = _Clock::now();
00335         if (_Clock::is_steady)
00336           {
00337             if (__now < __atime)
00338               sleep_for(__atime - __now);
00339             return;
00340           }
00341         while (__now < __atime)
00342           {
00343             sleep_for(__atime - __now);
00344             __now = _Clock::now();
00345           }
00346       }
00347 
00348   _GLIBCXX_END_NAMESPACE_VERSION
00349   }
00350 
00351   // @} group threads
00352 
00353 } // namespace
00354 
00355 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
00356 
00357 #endif // C++11
00358 
00359 #endif // _GLIBCXX_THREAD