posix_thread.hpp 1.9 KB

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