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