posix_thread.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. #ifndef BOOST_ASIO_DETAIL_POSIX_THREAD_HPP
  11. #define BOOST_ASIO_DETAIL_POSIX_THREAD_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/config.hpp>
  16. #if defined(BOOST_ASIO_HAS_PTHREADS)
  17. #include <cstddef>
  18. #include <pthread.h>
  19. #include <boost/asio/detail/noncopyable.hpp>
  20. #include <boost/asio/detail/push_options.hpp>
  21. namespace boost {
  22. namespace asio {
  23. namespace detail {
  24. extern "C"
  25. {
  26. BOOST_ASIO_DECL void* boost_asio_detail_posix_thread_function(void* arg);
  27. }
  28. class posix_thread
  29. : private noncopyable
  30. {
  31. public:
  32. // Constructor.
  33. template <typename Function>
  34. posix_thread(Function f, unsigned int = 0)
  35. : joined_(false)
  36. {
  37. start_thread(new func<Function>(f));
  38. }
  39. // Destructor.
  40. BOOST_ASIO_DECL ~posix_thread();
  41. // Wait for the thread to exit.
  42. BOOST_ASIO_DECL void join();
  43. // Get number of CPUs.
  44. BOOST_ASIO_DECL static std::size_t hardware_concurrency();
  45. private:
  46. friend void* boost_asio_detail_posix_thread_function(void* arg);
  47. class func_base
  48. {
  49. public:
  50. virtual ~func_base() {}
  51. virtual void run() = 0;
  52. };
  53. struct auto_func_base_ptr
  54. {
  55. func_base* ptr;
  56. ~auto_func_base_ptr() { delete ptr; }
  57. };
  58. template <typename Function>
  59. class func
  60. : public func_base
  61. {
  62. public:
  63. func(Function f)
  64. : f_(f)
  65. {
  66. }
  67. virtual void run()
  68. {
  69. f_();
  70. }
  71. private:
  72. Function f_;
  73. };
  74. BOOST_ASIO_DECL void start_thread(func_base* arg);
  75. ::pthread_t thread_;
  76. bool joined_;
  77. };
  78. } // namespace detail
  79. } // namespace asio
  80. } // namespace boost
  81. #include <boost/asio/detail/pop_options.hpp>
  82. #if defined(BOOST_ASIO_HEADER_ONLY)
  83. # include <boost/asio/detail/impl/posix_thread.ipp>
  84. #endif // defined(BOOST_ASIO_HEADER_ONLY)
  85. #endif // defined(BOOST_ASIO_HAS_PTHREADS)
  86. #endif // BOOST_ASIO_DETAIL_POSIX_THREAD_HPP