wince_thread.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. //
  2. // detail/wince_thread.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2011 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_WINCE_THREAD_HPP
  11. #define ASIO_DETAIL_WINCE_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(BOOST_WINDOWS) && defined(UNDER_CE)
  17. #include <memory>
  18. #include "asio/detail/noncopyable.hpp"
  19. #include "asio/detail/socket_types.hpp"
  20. #include "asio/detail/throw_error.hpp"
  21. #include "asio/error.hpp"
  22. #include "asio/detail/push_options.hpp"
  23. namespace asio {
  24. namespace detail {
  25. DWORD WINAPI wince_thread_function(LPVOID arg);
  26. class wince_thread
  27. : private noncopyable
  28. {
  29. public:
  30. // Constructor.
  31. template <typename Function>
  32. wince_thread(Function f)
  33. {
  34. std::auto_ptr<func_base> arg(new func<Function>(f));
  35. DWORD thread_id = 0;
  36. thread_ = ::CreateThread(0, 0, wince_thread_function,
  37. arg.get(), 0, &thread_id);
  38. if (!thread_)
  39. {
  40. DWORD last_error = ::GetLastError();
  41. asio::error_code ec(last_error,
  42. asio::error::get_system_category());
  43. asio::detail::throw_error(ec, "thread");
  44. }
  45. arg.release();
  46. }
  47. // Destructor.
  48. ~wince_thread()
  49. {
  50. ::CloseHandle(thread_);
  51. }
  52. // Wait for the thread to exit.
  53. void join()
  54. {
  55. ::WaitForSingleObject(thread_, INFINITE);
  56. }
  57. private:
  58. friend DWORD WINAPI wince_thread_function(LPVOID arg);
  59. class func_base
  60. {
  61. public:
  62. virtual ~func_base() {}
  63. virtual void run() = 0;
  64. };
  65. template <typename Function>
  66. class func
  67. : public func_base
  68. {
  69. public:
  70. func(Function f)
  71. : f_(f)
  72. {
  73. }
  74. virtual void run()
  75. {
  76. f_();
  77. }
  78. private:
  79. Function f_;
  80. };
  81. ::HANDLE thread_;
  82. };
  83. inline DWORD WINAPI wince_thread_function(LPVOID arg)
  84. {
  85. std::auto_ptr<wince_thread::func_base> func(
  86. static_cast<wince_thread::func_base*>(arg));
  87. func->run();
  88. return 0;
  89. }
  90. } // namespace detail
  91. } // namespace asio
  92. #include "asio/detail/pop_options.hpp"
  93. #endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
  94. #endif // ASIO_DETAIL_WINCE_THREAD_HPP