1 // 2 // detail/posix_thread.hpp 3 // ~~~~~~~~~~~~~~~~~~~~~~~ 4 // 5 // Copyright (c) 2003-2016 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 ASIO_DETAIL_POSIX_THREAD_HPP 12 #define 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 "asio/detail/config.hpp" 19 20 #if defined(ASIO_HAS_PTHREADS) 21 22 #include <pthread.h> 23 #include "asio/detail/noncopyable.hpp" 24 25 #include "asio/detail/push_options.hpp" 26 27 namespace asio { 28 namespace detail { 29 30 extern "C" 31 { 32 ASIO_DECL void* asio_detail_posix_thread_function(void* arg); 33 } 34 35 class posix_thread 36 : private noncopyable 37 { 38 public: 39 // Constructor. 40 template <typename Function> posix_thread(Function f,unsigned int=0)41 posix_thread(Function f, unsigned int = 0) 42 : joined_(false) 43 { 44 start_thread(new func<Function>(f)); 45 } 46 47 // Destructor. 48 ASIO_DECL ~posix_thread(); 49 50 // Wait for the thread to exit. 51 ASIO_DECL void join(); 52 53 private: 54 friend void* asio_detail_posix_thread_function(void* arg); 55 56 class func_base 57 { 58 public: ~func_base()59 virtual ~func_base() {} 60 virtual void run() = 0; 61 }; 62 63 struct auto_func_base_ptr 64 { 65 func_base* ptr; ~auto_func_base_ptrasio::detail::posix_thread::auto_func_base_ptr66 ~auto_func_base_ptr() { delete ptr; } 67 }; 68 69 template <typename Function> 70 class func 71 : public func_base 72 { 73 public: func(Function f)74 func(Function f) 75 : f_(f) 76 { 77 } 78 run()79 virtual void run() 80 { 81 f_(); 82 } 83 84 private: 85 Function f_; 86 }; 87 88 ASIO_DECL void start_thread(func_base* arg); 89 90 ::pthread_t thread_; 91 bool joined_; 92 }; 93 94 } // namespace detail 95 } // namespace asio 96 97 #include "asio/detail/pop_options.hpp" 98 99 #if defined(ASIO_HEADER_ONLY) 100 # include "asio/detail/impl/posix_thread.ipp" 101 #endif // defined(ASIO_HEADER_ONLY) 102 103 #endif // defined(ASIO_HAS_PTHREADS) 104 105 #endif // ASIO_DETAIL_POSIX_THREAD_HPP 106