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