thread revision 232950
1// -*- C++ -*-
2//===--------------------------- thread -----------------------------------===//
3//
4//                     The LLVM Compiler Infrastructure
5//
6// This file is dual licensed under the MIT and the University of Illinois Open
7// Source Licenses. See LICENSE.TXT for details.
8//
9//===----------------------------------------------------------------------===//
10
11#ifndef _LIBCPP_THREAD
12#define _LIBCPP_THREAD
13
14/*
15
16    thread synopsis
17
18#define __STDCPP_THREADS__ __cplusplus
19
20namespace std
21{
22
23class thread
24{
25public:
26    class id;
27    typedef pthread_t native_handle_type;
28
29    thread();
30    template <class F, class ...Args> explicit thread(F&& f, Args&&... args);
31    ~thread();
32
33    thread(const thread&) = delete;
34    thread(thread&& t);
35
36    thread& operator=(const thread&) = delete;
37    thread& operator=(thread&& t);
38
39    void swap(thread& t);
40
41    bool joinable() const;
42    void join();
43    void detach();
44    id get_id() const;
45    native_handle_type native_handle();
46
47    static unsigned hardware_concurrency();
48};
49
50void swap(thread& x, thread& y);
51
52class thread::id
53{
54public:
55    id();
56};
57
58bool operator==(thread::id x, thread::id y);
59bool operator!=(thread::id x, thread::id y);
60bool operator< (thread::id x, thread::id y);
61bool operator<=(thread::id x, thread::id y);
62bool operator> (thread::id x, thread::id y);
63bool operator>=(thread::id x, thread::id y);
64
65template<class charT, class traits>
66basic_ostream<charT, traits>&
67operator<<(basic_ostream<charT, traits>& out, thread::id id);
68
69namespace this_thread
70{
71
72thread::id get_id();
73
74void yield();
75
76template <class Clock, class Duration>
77void sleep_until(const chrono::time_point<Clock, Duration>& abs_time);
78
79template <class Rep, class Period>
80void sleep_for(const chrono::duration<Rep, Period>& rel_time);
81
82}  // this_thread
83
84}  // std
85
86*/
87
88#include <__config>
89#include <iosfwd>
90#include <__functional_base>
91#include <type_traits>
92#include <cstddef>
93#include <functional>
94#include <memory>
95#include <system_error>
96#include <chrono>
97#include <__mutex_base>
98#ifndef _LIBCPP_HAS_NO_VARIADICS
99#include <tuple>
100#endif
101#include <pthread.h>
102
103#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
104#pragma GCC system_header
105#endif
106
107#define __STDCPP_THREADS__ __cplusplus
108
109_LIBCPP_BEGIN_NAMESPACE_STD
110
111template <class _Tp>
112class __thread_specific_ptr
113{
114    pthread_key_t __key_;
115
116    __thread_specific_ptr(const __thread_specific_ptr&);
117    __thread_specific_ptr& operator=(const __thread_specific_ptr&);
118
119    static void __at_thread_exit(void*);
120public:
121    typedef _Tp* pointer;
122
123    __thread_specific_ptr();
124    ~__thread_specific_ptr();
125
126    _LIBCPP_INLINE_VISIBILITY
127    pointer get() const {return static_cast<_Tp*>(pthread_getspecific(__key_));}
128    _LIBCPP_INLINE_VISIBILITY
129    pointer operator*() const {return *get();}
130    _LIBCPP_INLINE_VISIBILITY
131    pointer operator->() const {return get();}
132    pointer release();
133    void reset(pointer __p = nullptr);
134};
135
136template <class _Tp>
137void
138__thread_specific_ptr<_Tp>::__at_thread_exit(void* __p)
139{
140    delete static_cast<pointer>(__p);
141}
142
143template <class _Tp>
144__thread_specific_ptr<_Tp>::__thread_specific_ptr()
145{
146    int __ec = pthread_key_create(&__key_, &__thread_specific_ptr::__at_thread_exit);
147    if (__ec)
148        throw system_error(error_code(__ec, system_category()),
149                           "__thread_specific_ptr construction failed");
150}
151
152template <class _Tp>
153__thread_specific_ptr<_Tp>::~__thread_specific_ptr()
154{
155    pthread_key_delete(__key_);
156}
157
158template <class _Tp>
159typename __thread_specific_ptr<_Tp>::pointer
160__thread_specific_ptr<_Tp>::release()
161{
162    pointer __p = get();
163    pthread_setspecific(__key_, 0);
164    return __p;
165}
166
167template <class _Tp>
168void
169__thread_specific_ptr<_Tp>::reset(pointer __p)
170{
171    pointer __p_old = get();
172    pthread_setspecific(__key_, __p);
173    delete __p_old;
174}
175
176class thread;
177class __thread_id;
178
179namespace this_thread
180{
181
182__thread_id get_id();
183
184}  // this_thread
185
186class _LIBCPP_VISIBLE __thread_id;
187template<> struct _LIBCPP_VISIBLE hash<__thread_id>;
188
189class _LIBCPP_VISIBLE __thread_id
190{
191    // FIXME: pthread_t is a pointer on Darwin but a long on Linux.
192    // NULL is the no-thread value on Darwin.  Someone needs to check
193    // on other platforms.  We assume 0 works everywhere for now.
194    pthread_t __id_;
195
196public:
197    _LIBCPP_INLINE_VISIBILITY
198    __thread_id() : __id_(0) {}
199
200    friend _LIBCPP_INLINE_VISIBILITY
201        bool operator==(__thread_id __x, __thread_id __y)
202        {return __x.__id_ == __y.__id_;}
203    friend _LIBCPP_INLINE_VISIBILITY
204        bool operator!=(__thread_id __x, __thread_id __y)
205        {return !(__x == __y);}
206    friend _LIBCPP_INLINE_VISIBILITY
207        bool operator< (__thread_id __x, __thread_id __y)
208        {return __x.__id_ < __y.__id_;}
209    friend _LIBCPP_INLINE_VISIBILITY
210        bool operator<=(__thread_id __x, __thread_id __y)
211        {return !(__y < __x);}
212    friend _LIBCPP_INLINE_VISIBILITY
213        bool operator> (__thread_id __x, __thread_id __y)
214        {return   __y < __x ;}
215    friend _LIBCPP_INLINE_VISIBILITY
216        bool operator>=(__thread_id __x, __thread_id __y)
217        {return !(__x < __y);}
218
219    template<class _CharT, class _Traits>
220    friend
221    _LIBCPP_INLINE_VISIBILITY
222    basic_ostream<_CharT, _Traits>&
223    operator<<(basic_ostream<_CharT, _Traits>& __os, __thread_id __id)
224        {return __os << __id.__id_;}
225
226private:
227    _LIBCPP_INLINE_VISIBILITY
228    __thread_id(pthread_t __id) : __id_(__id) {}
229
230    friend __thread_id this_thread::get_id();
231    friend class _LIBCPP_VISIBLE thread;
232    friend struct _LIBCPP_VISIBLE hash<__thread_id>;
233};
234
235template<>
236struct _LIBCPP_VISIBLE hash<__thread_id>
237    : public unary_function<__thread_id, size_t>
238{
239    _LIBCPP_INLINE_VISIBILITY
240    size_t operator()(__thread_id __v) const
241    {
242        return hash<pthread_t>()(__v.__id_);
243    }
244};
245
246namespace this_thread
247{
248
249inline _LIBCPP_INLINE_VISIBILITY
250__thread_id
251get_id()
252{
253    return pthread_self();
254}
255
256}  // this_thread
257
258class _LIBCPP_VISIBLE thread
259{
260    pthread_t __t_;
261
262    thread(const thread&);
263    thread& operator=(const thread&);
264public:
265    typedef __thread_id id;
266    typedef pthread_t native_handle_type;
267
268    _LIBCPP_INLINE_VISIBILITY
269    thread() : __t_(0) {}
270#ifndef _LIBCPP_HAS_NO_VARIADICS
271    template <class _Fp, class ..._Args,
272              class = typename enable_if
273              <
274                   !is_same<typename decay<_Fp>::type, thread>::value
275              >::type
276             >
277        explicit thread(_Fp&& __f, _Args&&... __args);
278#else  // _LIBCPP_HAS_NO_VARIADICS
279    template <class _Fp> explicit thread(_Fp __f);
280#endif
281    ~thread();
282
283#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
284    _LIBCPP_INLINE_VISIBILITY
285    thread(thread&& __t) : __t_(__t.__t_) {__t.__t_ = 0;}
286    thread& operator=(thread&& __t);
287#endif  // _LIBCPP_HAS_NO_RVALUE_REFERENCES
288
289    _LIBCPP_INLINE_VISIBILITY
290    void swap(thread& __t) {_VSTD::swap(__t_, __t.__t_);}
291
292    _LIBCPP_INLINE_VISIBILITY
293    bool joinable() const {return __t_ != 0;}
294    void join();
295    void detach();
296    _LIBCPP_INLINE_VISIBILITY
297    id get_id() const {return __t_;}
298    _LIBCPP_INLINE_VISIBILITY
299    native_handle_type native_handle() {return __t_;}
300
301    static unsigned hardware_concurrency();
302};
303
304class __assoc_sub_state;
305
306class _LIBCPP_HIDDEN __thread_struct_imp;
307
308class __thread_struct
309{
310    __thread_struct_imp* __p_;
311
312    __thread_struct(const __thread_struct&);
313    __thread_struct& operator=(const __thread_struct&);
314public:
315    __thread_struct();
316    ~__thread_struct();
317
318    void notify_all_at_thread_exit(condition_variable*, mutex*);
319    void __make_ready_at_thread_exit(__assoc_sub_state*);
320};
321
322__thread_specific_ptr<__thread_struct>& __thread_local_data();
323
324#ifndef _LIBCPP_HAS_NO_VARIADICS
325
326template <class _Fp, class ..._Args, size_t ..._Indices>
327inline _LIBCPP_INLINE_VISIBILITY
328void
329__threaad_execute(tuple<_Fp, _Args...>& __t, __tuple_indices<_Indices...>)
330{
331    __invoke(_VSTD::move(_VSTD::get<0>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);
332}
333
334template <class _Fp>
335void*
336__thread_proxy(void* __vp)
337{
338    __thread_local_data().reset(new __thread_struct);
339    std::unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp));
340    typedef typename __make_tuple_indices<tuple_size<_Fp>::value, 1>::type _Index;
341    __threaad_execute(*__p, _Index());
342    return nullptr;
343}
344
345template <class _Fp, class ..._Args,
346          class
347         >
348thread::thread(_Fp&& __f, _Args&&... __args)
349{
350    typedef tuple<typename decay<_Fp>::type, typename decay<_Args>::type...> _Gp;
351    _VSTD::unique_ptr<_Gp> __p(new _Gp(__decay_copy(_VSTD::forward<_Fp>(__f)),
352                                __decay_copy(_VSTD::forward<_Args>(__args))...));
353    int __ec = pthread_create(&__t_, 0, &__thread_proxy<_Gp>, __p.get());
354    if (__ec == 0)
355        __p.release();
356    else
357        __throw_system_error(__ec, "thread constructor failed");
358}
359
360#else  // _LIBCPP_HAS_NO_VARIADICS
361
362template <class _Fp>
363void*
364__thread_proxy(void* __vp)
365{
366    __thread_local_data().reset(new __thread_struct);
367    std::unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp));
368    (*__p)();
369    return nullptr;
370}
371
372template <class _Fp>
373thread::thread(_Fp __f)
374{
375    std::unique_ptr<_Fp> __p(new _Fp(__f));
376    int __ec = pthread_create(&__t_, 0, &__thread_proxy<_Fp>, __p.get());
377    if (__ec == 0)
378        __p.release();
379    else
380        __throw_system_error(__ec, "thread constructor failed");
381}
382
383#endif  // _LIBCPP_HAS_NO_VARIADICS
384
385#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
386
387inline _LIBCPP_INLINE_VISIBILITY
388thread&
389thread::operator=(thread&& __t)
390{
391    if (__t_ != 0)
392        terminate();
393    __t_ = __t.__t_;
394    __t.__t_ = 0;
395    return *this;
396}
397
398#endif  // _LIBCPP_HAS_NO_RVALUE_REFERENCES
399
400inline _LIBCPP_INLINE_VISIBILITY
401void swap(thread& __x, thread& __y) {__x.swap(__y);}
402
403namespace this_thread
404{
405
406void sleep_for(const chrono::nanoseconds& ns);
407
408template <class _Rep, class _Period>
409void
410sleep_for(const chrono::duration<_Rep, _Period>& __d)
411{
412    using namespace chrono;
413    nanoseconds __ns = duration_cast<nanoseconds>(__d);
414    if (__ns < __d)
415        ++__ns;
416    sleep_for(__ns);
417}
418
419template <class _Clock, class _Duration>
420void
421sleep_until(const chrono::time_point<_Clock, _Duration>& __t)
422{
423    using namespace chrono;
424    mutex __mut;
425    condition_variable __cv;
426    unique_lock<mutex> __lk(__mut);
427    while (_Clock::now() < __t)
428        __cv.wait_until(__lk, __t);
429}
430
431template <class _Duration>
432inline _LIBCPP_INLINE_VISIBILITY
433void
434sleep_until(const chrono::time_point<chrono::steady_clock, _Duration>& __t)
435{
436    using namespace chrono;
437    sleep_for(__t - steady_clock::now());
438}
439
440inline _LIBCPP_INLINE_VISIBILITY
441void yield() {sched_yield();}
442
443}  // this_thread
444
445_LIBCPP_END_NAMESPACE_STD
446
447#endif  // _LIBCPP_THREAD
448