Line data Source code
1 : // <thread> -*- C++ -*-
2 :
3 : // Copyright (C) 2008-2018 Free Software Foundation, Inc.
4 : //
5 : // This file is part of the GNU ISO C++ Library. This library is free
6 : // software; you can redistribute it and/or modify it under the
7 : // terms of the GNU General Public License as published by the
8 : // Free Software Foundation; either version 3, or (at your option)
9 : // any later version.
10 :
11 : // This library is distributed in the hope that it will be useful,
12 : // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 : // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 : // GNU General Public License for more details.
15 :
16 : // Under Section 7 of GPL version 3, you are granted additional
17 : // permissions described in the GCC Runtime Library Exception, version
18 : // 3.1, as published by the Free Software Foundation.
19 :
20 : // You should have received a copy of the GNU General Public License and
21 : // a copy of the GCC Runtime Library Exception along with this program;
22 : // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 : // <http://www.gnu.org/licenses/>.
24 :
25 : /** @file include/thread
26 : * This is a Standard C++ Library header.
27 : */
28 :
29 : #ifndef _GLIBCXX_THREAD
30 : #define _GLIBCXX_THREAD 1
31 :
32 : #pragma GCC system_header
33 :
34 : #if __cplusplus < 201103L
35 : # include <bits/c++0x_warning.h>
36 : #else
37 :
38 : #include <chrono>
39 : #include <memory>
40 : #include <tuple>
41 : #include <cerrno>
42 : #include <bits/functexcept.h>
43 : #include <bits/functional_hash.h>
44 : #include <bits/invoke.h>
45 : #include <bits/gthr.h>
46 :
47 : #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
48 :
49 : namespace std _GLIBCXX_VISIBILITY(default)
50 : {
51 : _GLIBCXX_BEGIN_NAMESPACE_VERSION
52 :
53 : /**
54 : * @defgroup threads Threads
55 : * @ingroup concurrency
56 : *
57 : * Classes for thread support.
58 : * @{
59 : */
60 :
61 : /// thread
62 : class thread
63 : {
64 : public:
65 : // Abstract base class for types that wrap arbitrary functors to be
66 : // invoked in the new thread of execution.
67 : struct _State
68 : {
69 : virtual ~_State();
70 : virtual void _M_run() = 0;
71 : };
72 : using _State_ptr = unique_ptr<_State>;
73 :
74 : typedef __gthread_t native_handle_type;
75 :
76 : /// thread::id
77 : class id
78 : {
79 : native_handle_type _M_thread;
80 :
81 : public:
82 1069 : id() noexcept : _M_thread() { }
83 :
84 : explicit
85 : id(native_handle_type __id) : _M_thread(__id) { }
86 :
87 : private:
88 : friend class thread;
89 : friend class hash<thread::id>;
90 :
91 : friend bool
92 : operator==(thread::id __x, thread::id __y) noexcept;
93 :
94 : friend bool
95 : operator<(thread::id __x, thread::id __y) noexcept;
96 :
97 : template<class _CharT, class _Traits>
98 : friend basic_ostream<_CharT, _Traits>&
99 : operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id);
100 : };
101 :
102 : private:
103 : id _M_id;
104 :
105 : // _GLIBCXX_RESOLVE_LIB_DEFECTS
106 : // 2097. packaged_task constructors should be constrained
107 : template<typename _Tp>
108 : using __not_same = __not_<is_same<
109 : typename remove_cv<typename remove_reference<_Tp>::type>::type,
110 : thread>>;
111 :
112 : public:
113 152 : thread() noexcept = default;
114 :
115 : template<typename _Callable, typename... _Args,
116 : typename = _Require<__not_same<_Callable>>>
117 : explicit
118 152 : thread(_Callable&& __f, _Args&&... __args)
119 152 : {
120 : static_assert( __is_invocable<typename decay<_Callable>::type,
121 : typename decay<_Args>::type...>::value,
122 : "std::thread arguments must be invocable after conversion to rvalues"
123 : );
124 :
125 : #ifdef GTHR_ACTIVE_PROXY
126 : // Create a reference to pthread_create, not just the gthr weak symbol.
127 152 : auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
128 : #else
129 : auto __depend = nullptr;
130 : #endif
131 152 : _M_start_thread(_S_make_state(
132 : __make_invoker(std::forward<_Callable>(__f),
133 : std::forward<_Args>(__args)...)),
134 : __depend);
135 152 : }
136 :
137 304 : ~thread()
138 304 : {
139 304 : if (joinable())
140 0 : std::terminate();
141 304 : }
142 :
143 : thread(const thread&) = delete;
144 :
145 : thread(thread&& __t) noexcept
146 : { swap(__t); }
147 :
148 : thread& operator=(const thread&) = delete;
149 :
150 152 : thread& operator=(thread&& __t) noexcept
151 : {
152 152 : if (joinable())
153 0 : std::terminate();
154 152 : swap(__t);
155 152 : return *this;
156 : }
157 :
158 : void
159 152 : swap(thread& __t) noexcept
160 152 : { std::swap(_M_id, __t._M_id); }
161 :
162 : bool
163 765 : joinable() const noexcept
164 765 : { return !(_M_id == id()); }
165 :
166 : void
167 : join();
168 :
169 : void
170 : detach();
171 :
172 : thread::id
173 : get_id() const noexcept
174 : { return _M_id; }
175 :
176 : /** @pre thread is joinable
177 : */
178 : native_handle_type
179 : native_handle()
180 : { return _M_id._M_thread; }
181 :
182 : // Returns a value that hints at the number of hardware thread contexts.
183 : static unsigned int
184 : hardware_concurrency() noexcept;
185 :
186 : private:
187 : template<typename _Callable>
188 : struct _State_impl : public _State
189 : {
190 : _Callable _M_func;
191 :
192 152 : _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))
193 152 : { }
194 :
195 : void
196 152 : _M_run() { _M_func(); }
197 : };
198 :
199 : void
200 : _M_start_thread(_State_ptr, void (*)());
201 :
202 : template<typename _Callable>
203 : static _State_ptr
204 152 : _S_make_state(_Callable&& __f)
205 : {
206 : using _Impl = _State_impl<_Callable>;
207 152 : return _State_ptr{new _Impl{std::forward<_Callable>(__f)}};
208 : }
209 : #if _GLIBCXX_THREAD_ABI_COMPAT
210 : public:
211 : struct _Impl_base;
212 : typedef shared_ptr<_Impl_base> __shared_base_type;
213 : struct _Impl_base
214 : {
215 : __shared_base_type _M_this_ptr;
216 : virtual ~_Impl_base() = default;
217 : virtual void _M_run() = 0;
218 : };
219 :
220 : private:
221 : void
222 : _M_start_thread(__shared_base_type, void (*)());
223 :
224 : void
225 : _M_start_thread(__shared_base_type);
226 : #endif
227 :
228 : private:
229 : // A call wrapper that does INVOKE(forwarded tuple elements...)
230 : template<typename _Tuple>
231 : struct _Invoker
232 : {
233 : _Tuple _M_t;
234 :
235 : template<size_t _Index>
236 : static __tuple_element_t<_Index, _Tuple>&&
237 : _S_declval();
238 :
239 : template<size_t... _Ind>
240 : auto
241 152 : _M_invoke(_Index_tuple<_Ind...>)
242 : noexcept(noexcept(std::__invoke(_S_declval<_Ind>()...)))
243 : -> decltype(std::__invoke(_S_declval<_Ind>()...))
244 152 : { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
245 :
246 : using _Indices
247 : = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
248 :
249 : auto
250 152 : operator()()
251 : noexcept(noexcept(std::declval<_Invoker&>()._M_invoke(_Indices())))
252 : -> decltype(std::declval<_Invoker&>()._M_invoke(_Indices()))
253 152 : { return _M_invoke(_Indices()); }
254 : };
255 :
256 : template<typename... _Tp>
257 : using __decayed_tuple = tuple<typename std::decay<_Tp>::type...>;
258 :
259 : public:
260 : // Returns a call wrapper that stores
261 : // tuple{DECAY_COPY(__callable), DECAY_COPY(__args)...}.
262 : template<typename _Callable, typename... _Args>
263 : static _Invoker<__decayed_tuple<_Callable, _Args...>>
264 152 : __make_invoker(_Callable&& __callable, _Args&&... __args)
265 : {
266 : return { __decayed_tuple<_Callable, _Args...>{
267 : std::forward<_Callable>(__callable), std::forward<_Args>(__args)...
268 152 : } };
269 : }
270 : };
271 :
272 : inline void
273 : swap(thread& __x, thread& __y) noexcept
274 : { __x.swap(__y); }
275 :
276 : inline bool
277 765 : operator==(thread::id __x, thread::id __y) noexcept
278 : {
279 : // pthread_equal is undefined if either thread ID is not valid, so we
280 : // can't safely use __gthread_equal on default-constructed values (nor
281 : // the non-zero value returned by this_thread::get_id() for
282 : // single-threaded programs using GNU libc). Assume EqualityComparable.
283 765 : return __x._M_thread == __y._M_thread;
284 : }
285 :
286 : inline bool
287 : operator!=(thread::id __x, thread::id __y) noexcept
288 : { return !(__x == __y); }
289 :
290 : inline bool
291 : operator<(thread::id __x, thread::id __y) noexcept
292 : {
293 : // Pthreads doesn't define any way to do this, so we just have to
294 : // assume native_handle_type is LessThanComparable.
295 : return __x._M_thread < __y._M_thread;
296 : }
297 :
298 : inline bool
299 : operator<=(thread::id __x, thread::id __y) noexcept
300 : { return !(__y < __x); }
301 :
302 : inline bool
303 : operator>(thread::id __x, thread::id __y) noexcept
304 : { return __y < __x; }
305 :
306 : inline bool
307 : operator>=(thread::id __x, thread::id __y) noexcept
308 : { return !(__x < __y); }
309 :
310 : // DR 889.
311 : /// std::hash specialization for thread::id.
312 : template<>
313 : struct hash<thread::id>
314 : : public __hash_base<size_t, thread::id>
315 : {
316 : size_t
317 : operator()(const thread::id& __id) const noexcept
318 : { return std::_Hash_impl::hash(__id._M_thread); }
319 : };
320 :
321 : template<class _CharT, class _Traits>
322 : inline basic_ostream<_CharT, _Traits>&
323 : operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
324 : {
325 : if (__id == thread::id())
326 : return __out << "thread::id of a non-executing thread";
327 : else
328 : return __out << __id._M_thread;
329 : }
330 :
331 : /** @namespace std::this_thread
332 : * @brief ISO C++ 2011 entities sub-namespace for thread.
333 : * 30.3.2 Namespace this_thread.
334 : */
335 : namespace this_thread
336 : {
337 : /// get_id
338 : inline thread::id
339 : get_id() noexcept
340 : {
341 : #ifdef __GLIBC__
342 : // For the GNU C library pthread_self() is usable without linking to
343 : // libpthread.so but returns 0, so we cannot use it in single-threaded
344 : // programs, because this_thread::get_id() != thread::id{} must be true.
345 : // We know that pthread_t is an integral type in the GNU C library.
346 : if (!__gthread_active_p())
347 : return thread::id(1);
348 : #endif
349 : return thread::id(__gthread_self());
350 : }
351 :
352 : /// yield
353 : inline void
354 : yield() noexcept
355 : {
356 : #ifdef _GLIBCXX_USE_SCHED_YIELD
357 : __gthread_yield();
358 : #endif
359 : }
360 :
361 : void
362 : __sleep_for(chrono::seconds, chrono::nanoseconds);
363 :
364 : /// sleep_for
365 : template<typename _Rep, typename _Period>
366 : inline void
367 : sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
368 : {
369 : if (__rtime <= __rtime.zero())
370 : return;
371 : auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
372 : auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
373 : #ifdef _GLIBCXX_USE_NANOSLEEP
374 : __gthread_time_t __ts =
375 : {
376 : static_cast<std::time_t>(__s.count()),
377 : static_cast<long>(__ns.count())
378 : };
379 : while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
380 : { }
381 : #else
382 : __sleep_for(__s, __ns);
383 : #endif
384 : }
385 :
386 : /// sleep_until
387 : template<typename _Clock, typename _Duration>
388 : inline void
389 : sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
390 : {
391 : auto __now = _Clock::now();
392 : if (_Clock::is_steady)
393 : {
394 : if (__now < __atime)
395 : sleep_for(__atime - __now);
396 : return;
397 : }
398 : while (__now < __atime)
399 : {
400 : sleep_for(__atime - __now);
401 : __now = _Clock::now();
402 : }
403 : }
404 : }
405 :
406 : // @} group threads
407 :
408 : _GLIBCXX_END_NAMESPACE_VERSION
409 : } // namespace
410 :
411 : #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
412 :
413 : #endif // C++11
414 :
415 : #endif // _GLIBCXX_THREAD
|