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     thread(const thread&&) = delete;
00123 
00124     thread(thread&& __t) noexcept
00125     { swap(__t); }
00126 
00127     template<typename _Callable, typename... _Args>
00128       explicit 
00129       thread(_Callable&& __f, _Args&&... __args)
00130       {
00131 #ifdef GTHR_ACTIVE_PROXY
00132         // Create a reference to pthread_create, not just the gthr weak symbol.
00133         auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
00134 #else
00135         auto __depend = nullptr;
00136 #endif
00137         _M_start_thread(_S_make_state(
00138               std::__bind_simple(std::forward<_Callable>(__f),
00139                                  std::forward<_Args>(__args)...)),
00140             __depend);
00141       }
00142 
00143     ~thread()
00144     {
00145       if (joinable())
00146         std::terminate();
00147     }
00148 
00149     thread& operator=(const thread&) = delete;
00150 
00151     thread& operator=(thread&& __t) noexcept
00152     {
00153       if (joinable())
00154         std::terminate();
00155       swap(__t);
00156       return *this;
00157     }
00158 
00159     void
00160     swap(thread& __t) noexcept
00161     { std::swap(_M_id, __t._M_id); }
00162 
00163     bool
00164     joinable() const noexcept
00165     { return !(_M_id == id()); }
00166 
00167     void
00168     join();
00169 
00170     void
00171     detach();
00172 
00173     thread::id
00174     get_id() const noexcept
00175     { return _M_id; }
00176 
00177     /** @pre thread is joinable
00178      */
00179     native_handle_type
00180     native_handle()
00181     { return _M_id._M_thread; }
00182 
00183     // Returns a value that hints at the number of hardware thread contexts.
00184     static unsigned int
00185     hardware_concurrency() noexcept;
00186 
00187   private:
00188     template<typename _Callable>
00189       struct _State_impl : public _State
00190       {
00191         _Callable               _M_func;
00192 
00193         _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))
00194         { }
00195 
00196         void
00197         _M_run() { _M_func(); }
00198       };
00199 
00200     void
00201     _M_start_thread(_State_ptr, void (*)());
00202 
00203     template<typename _Callable>
00204       static _State_ptr
00205       _S_make_state(_Callable&& __f)
00206       {
00207         using _Impl = _State_impl<_Callable>;
00208         return _State_ptr{new _Impl{std::forward<_Callable>(__f)}};
00209       }
00210 #if _GLIBCXX_THREAD_ABI_COMPAT
00211   public:
00212     struct _Impl_base;
00213     typedef shared_ptr<_Impl_base>      __shared_base_type;
00214     struct _Impl_base
00215     {
00216       __shared_base_type        _M_this_ptr;
00217       virtual ~_Impl_base() = default;
00218       virtual void _M_run() = 0;
00219     };
00220 
00221   private:
00222     void
00223     _M_start_thread(__shared_base_type, void (*)());
00224 
00225     void
00226     _M_start_thread(__shared_base_type);
00227 #endif
00228   };
00229 
00230   inline void
00231   swap(thread& __x, thread& __y) noexcept
00232   { __x.swap(__y); }
00233 
00234   inline bool
00235   operator!=(thread::id __x, thread::id __y) noexcept
00236   { return !(__x == __y); }
00237 
00238   inline bool
00239   operator<=(thread::id __x, thread::id __y) noexcept
00240   { return !(__y < __x); }
00241 
00242   inline bool
00243   operator>(thread::id __x, thread::id __y) noexcept
00244   { return __y < __x; }
00245 
00246   inline bool
00247   operator>=(thread::id __x, thread::id __y) noexcept
00248   { return !(__x < __y); }
00249 
00250   // DR 889.
00251   /// std::hash specialization for thread::id.
00252   template<>
00253     struct hash<thread::id>
00254     : public __hash_base<size_t, thread::id>
00255     {
00256       size_t
00257       operator()(const thread::id& __id) const noexcept
00258       { return std::_Hash_impl::hash(__id._M_thread); }
00259     };
00260 
00261   template<class _CharT, class _Traits>
00262     inline basic_ostream<_CharT, _Traits>&
00263     operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
00264     {
00265       if (__id == thread::id())
00266         return __out << "thread::id of a non-executing thread";
00267       else
00268         return __out << __id._M_thread;
00269     }
00270 
00271 _GLIBCXX_END_NAMESPACE_VERSION
00272 
00273   /** @namespace std::this_thread
00274    *  @brief ISO C++ 2011 entities sub-namespace for thread.
00275    *  30.3.2 Namespace this_thread.
00276    */
00277   namespace this_thread
00278   {
00279   _GLIBCXX_BEGIN_NAMESPACE_VERSION
00280 
00281     /// get_id
00282     inline thread::id
00283     get_id() noexcept
00284     {
00285 #ifdef __GLIBC__
00286       // For the GNU C library pthread_self() is usable without linking to
00287       // libpthread.so but returns 0, so we cannot use it in single-threaded
00288       // programs, because this_thread::get_id() != thread::id{} must be true.
00289       // We know that pthread_t is an integral type in the GNU C library.
00290       if (!__gthread_active_p())
00291         return thread::id(1);
00292 #endif
00293       return thread::id(__gthread_self());
00294     }
00295 
00296     /// yield
00297     inline void
00298     yield() noexcept
00299     {
00300 #ifdef _GLIBCXX_USE_SCHED_YIELD
00301       __gthread_yield();
00302 #endif
00303     }
00304 
00305     void
00306     __sleep_for(chrono::seconds, chrono::nanoseconds);
00307 
00308     /// sleep_for
00309     template<typename _Rep, typename _Period>
00310       inline void
00311       sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
00312       {
00313         if (__rtime <= __rtime.zero())
00314           return;
00315         auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
00316         auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
00317 #ifdef _GLIBCXX_USE_NANOSLEEP
00318         __gthread_time_t __ts =
00319           {
00320             static_cast<std::time_t>(__s.count()),
00321             static_cast<long>(__ns.count())
00322           };
00323         while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
00324           { }
00325 #else
00326         __sleep_for(__s, __ns);
00327 #endif
00328       }
00329 
00330     /// sleep_until
00331     template<typename _Clock, typename _Duration>
00332       inline void
00333       sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
00334       {
00335         auto __now = _Clock::now();
00336         if (_Clock::is_steady)
00337           {
00338             if (__now < __atime)
00339               sleep_for(__atime - __now);
00340             return;
00341           }
00342         while (__now < __atime)
00343           {
00344             sleep_for(__atime - __now);
00345             __now = _Clock::now();
00346           }
00347       }
00348 
00349   _GLIBCXX_END_NAMESPACE_VERSION
00350   }
00351 
00352   // @} group threads
00353 
00354 } // namespace
00355 
00356 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
00357 
00358 #endif // C++11
00359 
00360 #endif // _GLIBCXX_THREAD