fix doc example typo
[boost.git] / boost / asio / detail / posix_thread.hpp
blob1e3861848152cd322615e151b0b271d8cb1151f0
1 //
2 // posix_thread.hpp
3 // ~~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2008 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 //
11 #ifndef BOOST_ASIO_DETAIL_POSIX_THREAD_HPP
12 #define BOOST_ASIO_DETAIL_POSIX_THREAD_HPP
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
15 # pragma once
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
18 #include <boost/asio/detail/push_options.hpp>
20 #include <boost/asio/detail/push_options.hpp>
21 #include <boost/config.hpp>
22 #include <boost/system/system_error.hpp>
23 #include <boost/asio/detail/pop_options.hpp>
25 #if defined(BOOST_HAS_PTHREADS)
27 #include <boost/asio/detail/push_options.hpp>
28 #include <memory>
29 #include <boost/throw_exception.hpp>
30 #include <pthread.h>
31 #include <boost/asio/detail/pop_options.hpp>
33 #include <boost/asio/error.hpp>
34 #include <boost/asio/detail/noncopyable.hpp>
36 namespace boost {
37 namespace asio {
38 namespace detail {
40 extern "C" void* asio_detail_posix_thread_function(void* arg);
42 class posix_thread
43 : private noncopyable
45 public:
46 // Constructor.
47 template <typename Function>
48 posix_thread(Function f)
49 : joined_(false)
51 std::auto_ptr<func_base> arg(new func<Function>(f));
52 int error = ::pthread_create(&thread_, 0,
53 asio_detail_posix_thread_function, arg.get());
54 if (error != 0)
56 boost::system::system_error e(
57 boost::system::error_code(error,
58 boost::asio::error::get_system_category()),
59 "thread");
60 boost::throw_exception(e);
62 arg.release();
65 // Destructor.
66 ~posix_thread()
68 if (!joined_)
69 ::pthread_detach(thread_);
72 // Wait for the thread to exit.
73 void join()
75 if (!joined_)
77 ::pthread_join(thread_, 0);
78 joined_ = true;
82 private:
83 friend void* asio_detail_posix_thread_function(void* arg);
85 class func_base
87 public:
88 virtual ~func_base() {}
89 virtual void run() = 0;
92 template <typename Function>
93 class func
94 : public func_base
96 public:
97 func(Function f)
98 : f_(f)
102 virtual void run()
104 f_();
107 private:
108 Function f_;
111 ::pthread_t thread_;
112 bool joined_;
115 inline void* asio_detail_posix_thread_function(void* arg)
117 std::auto_ptr<posix_thread::func_base> f(
118 static_cast<posix_thread::func_base*>(arg));
119 f->run();
120 return 0;
123 } // namespace detail
124 } // namespace asio
125 } // namespace boost
127 #endif // defined(BOOST_HAS_PTHREADS)
129 #include <boost/asio/detail/pop_options.hpp>
131 #endif // BOOST_ASIO_DETAIL_POSIX_THREAD_HPP