posix_thread.hpp 2.0 KB

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