00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011 #ifndef ASIO_DETAIL_POSIX_THREAD_HPP
00012 #define ASIO_DETAIL_POSIX_THREAD_HPP
00013
00014 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
00015 # pragma once
00016 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
00017
00018 #include "asio/detail/push_options.hpp"
00019
00020 #include "asio/detail/push_options.hpp"
00021 #include <boost/config.hpp>
00022 #include "asio/detail/pop_options.hpp"
00023
00024 #if defined(BOOST_HAS_PTHREADS)
00025
00026 #include "asio/detail/push_options.hpp"
00027 #include <memory>
00028 #include <boost/throw_exception.hpp>
00029 #include <pthread.h>
00030 #include "asio/detail/pop_options.hpp"
00031
00032 #include "asio/system_error.hpp"
00033 #include "asio/detail/noncopyable.hpp"
00034
00035 namespace asio {
00036 namespace detail {
00037
00038 extern "C" void* asio_detail_posix_thread_function(void* arg);
00039
00040 class posix_thread
00041 : private noncopyable
00042 {
00043 public:
00044
00045 template <typename Function>
00046 posix_thread(Function f)
00047 : joined_(false)
00048 {
00049 std::auto_ptr<func_base> arg(new func<Function>(f));
00050 int error = ::pthread_create(&thread_, 0,
00051 asio_detail_posix_thread_function, arg.get());
00052 if (error != 0)
00053 {
00054 asio::system_error e(
00055 asio::error_code(error, asio::native_ecat),
00056 "thread");
00057 boost::throw_exception(e);
00058 }
00059 arg.release();
00060 }
00061
00062
00063 ~posix_thread()
00064 {
00065 if (!joined_)
00066 ::pthread_detach(thread_);
00067 }
00068
00069
00070 void join()
00071 {
00072 if (!joined_)
00073 {
00074 ::pthread_join(thread_, 0);
00075 joined_ = true;
00076 }
00077 }
00078
00079 private:
00080 friend void* asio_detail_posix_thread_function(void* arg);
00081
00082 class func_base
00083 {
00084 public:
00085 virtual ~func_base() {}
00086 virtual void run() = 0;
00087 };
00088
00089 template <typename Function>
00090 class func
00091 : public func_base
00092 {
00093 public:
00094 func(Function f)
00095 : f_(f)
00096 {
00097 }
00098
00099 virtual void run()
00100 {
00101 f_();
00102 }
00103
00104 private:
00105 Function f_;
00106 };
00107
00108 ::pthread_t thread_;
00109 bool joined_;
00110 };
00111
00112 inline void* asio_detail_posix_thread_function(void* arg)
00113 {
00114 std::auto_ptr<posix_thread::func_base> f(
00115 static_cast<posix_thread::func_base*>(arg));
00116 f->run();
00117 return 0;
00118 }
00119
00120 }
00121 }
00122
00123 #endif // defined(BOOST_HAS_PTHREADS)
00124
00125 #include "asio/detail/pop_options.hpp"
00126
00127 #endif // ASIO_DETAIL_POSIX_THREAD_HPP