1 //
2 // detail/posix_thread.hpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
6 //
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9 //
10 
11 #ifndef BOOST_ASIO_DETAIL_POSIX_THREAD_HPP
12 #define BOOST_ASIO_DETAIL_POSIX_THREAD_HPP
13 
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
15 # pragma once
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
17 
18 #include <boost/asio/detail/config.hpp>
19 
20 #if defined(BOOST_ASIO_HAS_PTHREADS)
21 
22 #include <pthread.h>
23 #include <boost/asio/detail/noncopyable.hpp>
24 
25 #include <boost/asio/detail/push_options.hpp>
26 
27 namespace boost {
28 namespace asio {
29 namespace detail {
30 
31 extern "C"
32 {
33   BOOST_ASIO_DECL void* boost_asio_detail_posix_thread_function(void* arg);
34 }
35 
36 class posix_thread
37   : private noncopyable
38 {
39 public:
40   // Constructor.
41   template <typename Function>
posix_thread(Function f,unsigned int=0)42   posix_thread(Function f, unsigned int = 0)
43     : joined_(false)
44   {
45     start_thread(new func<Function>(f));
46   }
47 
48   // Destructor.
49   BOOST_ASIO_DECL ~posix_thread();
50 
51   // Wait for the thread to exit.
52   BOOST_ASIO_DECL void join();
53 
54 private:
55   friend void* boost_asio_detail_posix_thread_function(void* arg);
56 
57   class func_base
58   {
59   public:
~func_base()60     virtual ~func_base() {}
61     virtual void run() = 0;
62   };
63 
64   struct auto_func_base_ptr
65   {
66     func_base* ptr;
~auto_func_base_ptrboost::asio::detail::posix_thread::auto_func_base_ptr67     ~auto_func_base_ptr() { delete ptr; }
68   };
69 
70   template <typename Function>
71   class func
72     : public func_base
73   {
74   public:
func(Function f)75     func(Function f)
76       : f_(f)
77     {
78     }
79 
run()80     virtual void run()
81     {
82       f_();
83     }
84 
85   private:
86     Function f_;
87   };
88 
89   BOOST_ASIO_DECL void start_thread(func_base* arg);
90 
91   ::pthread_t thread_;
92   bool joined_;
93 };
94 
95 } // namespace detail
96 } // namespace asio
97 } // namespace boost
98 
99 #include <boost/asio/detail/pop_options.hpp>
100 
101 #if defined(BOOST_ASIO_HEADER_ONLY)
102 # include <boost/asio/detail/impl/posix_thread.ipp>
103 #endif // defined(BOOST_ASIO_HEADER_ONLY)
104 
105 #endif // defined(BOOST_ASIO_HAS_PTHREADS)
106 
107 #endif // BOOST_ASIO_DETAIL_POSIX_THREAD_HPP
108