xref: /llvm-project-15.0.7/libcxx/include/thread (revision 8fa2e679)
1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP_THREAD
11#define _LIBCPP_THREAD
12
13/*
14
15    thread synopsis
16
17namespace std
18{
19
20class thread
21{
22public:
23    class id;
24    typedef pthread_t native_handle_type;
25
26    thread() noexcept;
27    template <class F, class ...Args> explicit thread(F&& f, Args&&... args);
28    ~thread();
29
30    thread(const thread&) = delete;
31    thread(thread&& t) noexcept;
32
33    thread& operator=(const thread&) = delete;
34    thread& operator=(thread&& t) noexcept;
35
36    void swap(thread& t) noexcept;
37
38    bool joinable() const noexcept;
39    void join();
40    void detach();
41    id get_id() const noexcept;
42    native_handle_type native_handle();
43
44    static unsigned hardware_concurrency() noexcept;
45};
46
47void swap(thread& x, thread& y) noexcept;
48
49class thread::id
50{
51public:
52    id() noexcept;
53};
54
55bool operator==(thread::id x, thread::id y) noexcept;
56bool operator!=(thread::id x, thread::id y) noexcept;
57bool operator< (thread::id x, thread::id y) noexcept;
58bool operator<=(thread::id x, thread::id y) noexcept;
59bool operator> (thread::id x, thread::id y) noexcept;
60bool operator>=(thread::id x, thread::id y) noexcept;
61
62template<class charT, class traits>
63basic_ostream<charT, traits>&
64operator<<(basic_ostream<charT, traits>& out, thread::id id);
65
66namespace this_thread
67{
68
69thread::id get_id() noexcept;
70
71void yield() noexcept;
72
73template <class Clock, class Duration>
74void sleep_until(const chrono::time_point<Clock, Duration>& abs_time);
75
76template <class Rep, class Period>
77void sleep_for(const chrono::duration<Rep, Period>& rel_time);
78
79}  // this_thread
80
81}  // std
82
83*/
84
85#include <__assert> // all public C++ headers provide the assertion handler
86#include <__config>
87#include <__functional/hash.h>
88#include <__mutex_base>
89#include <__thread/poll_with_backoff.h>
90#include <__thread/timed_backoff_policy.h>
91#include <__threading_support>
92#include <__utility/forward.h>
93#include <cstddef>
94#include <iosfwd>
95#include <memory>
96#include <system_error>
97#include <tuple>
98#include <type_traits>
99#include <version>
100
101// standard-mandated includes
102#include <compare>
103
104#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
105#  pragma GCC system_header
106#endif
107
108_LIBCPP_PUSH_MACROS
109#include <__undef_macros>
110
111#ifdef _LIBCPP_HAS_NO_THREADS
112# error "<thread> is not supported since libc++ has been configured without support for threads."
113#endif
114
115_LIBCPP_BEGIN_NAMESPACE_STD
116
117template <class _Tp> class __thread_specific_ptr;
118class _LIBCPP_TYPE_VIS __thread_struct;
119class _LIBCPP_HIDDEN __thread_struct_imp;
120class __assoc_sub_state;
121
122_LIBCPP_FUNC_VIS __thread_specific_ptr<__thread_struct>& __thread_local_data();
123
124class _LIBCPP_TYPE_VIS __thread_struct
125{
126    __thread_struct_imp* __p_;
127
128    __thread_struct(const __thread_struct&);
129    __thread_struct& operator=(const __thread_struct&);
130public:
131    __thread_struct();
132    ~__thread_struct();
133
134    void notify_all_at_thread_exit(condition_variable*, mutex*);
135    void __make_ready_at_thread_exit(__assoc_sub_state*);
136};
137
138template <class _Tp>
139class __thread_specific_ptr
140{
141    __libcpp_tls_key __key_;
142
143     // Only __thread_local_data() may construct a __thread_specific_ptr
144     // and only with _Tp == __thread_struct.
145    static_assert((is_same<_Tp, __thread_struct>::value), "");
146    __thread_specific_ptr();
147    friend _LIBCPP_FUNC_VIS __thread_specific_ptr<__thread_struct>& __thread_local_data();
148
149    __thread_specific_ptr(const __thread_specific_ptr&);
150    __thread_specific_ptr& operator=(const __thread_specific_ptr&);
151
152    _LIBCPP_HIDDEN static void _LIBCPP_TLS_DESTRUCTOR_CC __at_thread_exit(void*);
153
154public:
155    typedef _Tp* pointer;
156
157    ~__thread_specific_ptr();
158
159    _LIBCPP_INLINE_VISIBILITY
160    pointer get() const {return static_cast<_Tp*>(__libcpp_tls_get(__key_));}
161    _LIBCPP_INLINE_VISIBILITY
162    pointer operator*() const {return *get();}
163    _LIBCPP_INLINE_VISIBILITY
164    pointer operator->() const {return get();}
165    void set_pointer(pointer __p);
166};
167
168template <class _Tp>
169void _LIBCPP_TLS_DESTRUCTOR_CC
170__thread_specific_ptr<_Tp>::__at_thread_exit(void* __p)
171{
172    delete static_cast<pointer>(__p);
173}
174
175template <class _Tp>
176__thread_specific_ptr<_Tp>::__thread_specific_ptr()
177{
178  int __ec =
179      __libcpp_tls_create(&__key_, &__thread_specific_ptr::__at_thread_exit);
180  if (__ec)
181    __throw_system_error(__ec, "__thread_specific_ptr construction failed");
182}
183
184template <class _Tp>
185__thread_specific_ptr<_Tp>::~__thread_specific_ptr()
186{
187    // __thread_specific_ptr is only created with a static storage duration
188    // so this destructor is only invoked during program termination. Invoking
189    // pthread_key_delete(__key_) may prevent other threads from deleting their
190    // thread local data. For this reason we leak the key.
191}
192
193template <class _Tp>
194void
195__thread_specific_ptr<_Tp>::set_pointer(pointer __p)
196{
197    _LIBCPP_ASSERT(get() == nullptr,
198                   "Attempting to overwrite thread local data");
199    __libcpp_tls_set(__key_, __p);
200}
201
202template<>
203struct _LIBCPP_TEMPLATE_VIS hash<__thread_id>
204    : public __unary_function<__thread_id, size_t>
205{
206    _LIBCPP_INLINE_VISIBILITY
207    size_t operator()(__thread_id __v) const _NOEXCEPT
208    {
209        return hash<__libcpp_thread_id>()(__v.__id_);
210    }
211};
212
213template<class _CharT, class _Traits>
214_LIBCPP_INLINE_VISIBILITY
215basic_ostream<_CharT, _Traits>&
216operator<<(basic_ostream<_CharT, _Traits>& __os, __thread_id __id)
217{return __os << __id.__id_;}
218
219class _LIBCPP_TYPE_VIS thread
220{
221    __libcpp_thread_t __t_;
222
223    thread(const thread&);
224    thread& operator=(const thread&);
225public:
226    typedef __thread_id id;
227    typedef __libcpp_thread_t native_handle_type;
228
229    _LIBCPP_INLINE_VISIBILITY
230    thread() _NOEXCEPT : __t_(_LIBCPP_NULL_THREAD) {}
231#ifndef _LIBCPP_CXX03_LANG
232    template <class _Fp, class ..._Args,
233              class = __enable_if_t<!is_same<__uncvref_t<_Fp>, thread>::value> >
234        _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
235        explicit thread(_Fp&& __f, _Args&&... __args);
236#else  // _LIBCPP_CXX03_LANG
237    template <class _Fp>
238    _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
239    explicit thread(_Fp __f);
240#endif
241    ~thread();
242
243    _LIBCPP_INLINE_VISIBILITY
244    thread(thread&& __t) _NOEXCEPT : __t_(__t.__t_) {
245        __t.__t_ = _LIBCPP_NULL_THREAD;
246    }
247
248    _LIBCPP_INLINE_VISIBILITY
249    thread& operator=(thread&& __t) _NOEXCEPT {
250        if (!__libcpp_thread_isnull(&__t_))
251            terminate();
252        __t_ = __t.__t_;
253        __t.__t_ = _LIBCPP_NULL_THREAD;
254        return *this;
255    }
256
257    _LIBCPP_INLINE_VISIBILITY
258    void swap(thread& __t) _NOEXCEPT {_VSTD::swap(__t_, __t.__t_);}
259
260    _LIBCPP_INLINE_VISIBILITY
261    bool joinable() const _NOEXCEPT {return !__libcpp_thread_isnull(&__t_);}
262    void join();
263    void detach();
264    _LIBCPP_INLINE_VISIBILITY
265    id get_id() const _NOEXCEPT {return __libcpp_thread_get_id(&__t_);}
266    _LIBCPP_INLINE_VISIBILITY
267    native_handle_type native_handle() _NOEXCEPT {return __t_;}
268
269    static unsigned hardware_concurrency() _NOEXCEPT;
270};
271
272#ifndef _LIBCPP_CXX03_LANG
273
274template <class _TSp, class _Fp, class ..._Args, size_t ..._Indices>
275inline _LIBCPP_INLINE_VISIBILITY
276void
277__thread_execute(tuple<_TSp, _Fp, _Args...>& __t, __tuple_indices<_Indices...>)
278{
279    _VSTD::__invoke(_VSTD::move(_VSTD::get<1>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);
280}
281
282template <class _Fp>
283_LIBCPP_INLINE_VISIBILITY
284void* __thread_proxy(void* __vp)
285{
286    // _Fp = tuple< unique_ptr<__thread_struct>, Functor, Args...>
287    unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp));
288    __thread_local_data().set_pointer(_VSTD::get<0>(*__p.get()).release());
289    typedef typename __make_tuple_indices<tuple_size<_Fp>::value, 2>::type _Index;
290    _VSTD::__thread_execute(*__p.get(), _Index());
291    return nullptr;
292}
293
294template <class _Fp, class ..._Args,
295          class
296         >
297thread::thread(_Fp&& __f, _Args&&... __args)
298{
299    typedef unique_ptr<__thread_struct> _TSPtr;
300    _TSPtr __tsp(new __thread_struct);
301    typedef tuple<_TSPtr, typename decay<_Fp>::type, typename decay<_Args>::type...> _Gp;
302    unique_ptr<_Gp> __p(
303            new _Gp(_VSTD::move(__tsp),
304                    _VSTD::forward<_Fp>(__f),
305                    _VSTD::forward<_Args>(__args)...));
306    int __ec = _VSTD::__libcpp_thread_create(&__t_, &__thread_proxy<_Gp>, __p.get());
307    if (__ec == 0)
308        __p.release();
309    else
310        __throw_system_error(__ec, "thread constructor failed");
311}
312
313#else  // _LIBCPP_CXX03_LANG
314
315template <class _Fp>
316struct __thread_invoke_pair {
317    // This type is used to pass memory for thread local storage and a functor
318    // to a newly created thread because std::pair doesn't work with
319    // std::unique_ptr in C++03.
320    __thread_invoke_pair(_Fp& __f) : __tsp_(new __thread_struct), __fn_(__f) {}
321    unique_ptr<__thread_struct> __tsp_;
322    _Fp __fn_;
323};
324
325template <class _Fp>
326void* __thread_proxy_cxx03(void* __vp)
327{
328    unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp));
329    __thread_local_data().set_pointer(__p->__tsp_.release());
330    (__p->__fn_)();
331    return nullptr;
332}
333
334template <class _Fp>
335thread::thread(_Fp __f)
336{
337
338    typedef __thread_invoke_pair<_Fp> _InvokePair;
339    typedef unique_ptr<_InvokePair> _PairPtr;
340    _PairPtr __pp(new _InvokePair(__f));
341    int __ec = _VSTD::__libcpp_thread_create(&__t_, &__thread_proxy_cxx03<_InvokePair>, __pp.get());
342    if (__ec == 0)
343        __pp.release();
344    else
345        __throw_system_error(__ec, "thread constructor failed");
346}
347
348#endif // _LIBCPP_CXX03_LANG
349
350inline _LIBCPP_INLINE_VISIBILITY
351void swap(thread& __x, thread& __y) _NOEXCEPT {__x.swap(__y);}
352
353namespace this_thread
354{
355
356_LIBCPP_FUNC_VIS void sleep_for(const chrono::nanoseconds& __ns);
357
358template <class _Rep, class _Period>
359void
360sleep_for(const chrono::duration<_Rep, _Period>& __d)
361{
362    if (__d > chrono::duration<_Rep, _Period>::zero())
363    {
364        // The standard guarantees a 64bit signed integer resolution for nanoseconds,
365        // so use INT64_MAX / 1e9 as cut-off point. Use a constant to avoid <climits>
366        // and issues with long double folding on PowerPC with GCC.
367        _LIBCPP_CONSTEXPR chrono::duration<long double> _Max =
368            chrono::duration<long double>(9223372036.0L);
369        chrono::nanoseconds __ns;
370        if (__d < _Max)
371        {
372            __ns = chrono::duration_cast<chrono::nanoseconds>(__d);
373            if (__ns < __d)
374                ++__ns;
375        }
376        else
377            __ns = chrono::nanoseconds::max();
378        this_thread::sleep_for(__ns);
379    }
380}
381
382template <class _Clock, class _Duration>
383void
384sleep_until(const chrono::time_point<_Clock, _Duration>& __t)
385{
386    mutex __mut;
387    condition_variable __cv;
388    unique_lock<mutex> __lk(__mut);
389    while (_Clock::now() < __t)
390        __cv.wait_until(__lk, __t);
391}
392
393template <class _Duration>
394inline _LIBCPP_INLINE_VISIBILITY
395void
396sleep_until(const chrono::time_point<chrono::steady_clock, _Duration>& __t)
397{
398    this_thread::sleep_for(__t - chrono::steady_clock::now());
399}
400
401inline _LIBCPP_INLINE_VISIBILITY
402void yield() _NOEXCEPT {__libcpp_thread_yield();}
403
404} // namespace this_thread
405
406_LIBCPP_END_NAMESPACE_STD
407
408_LIBCPP_POP_MACROS
409
410#endif // _LIBCPP_THREAD
411