RCFProto
 All Classes Functions Typedefs
win_thread.hpp
1 
2 //******************************************************************************
3 // RCF - Remote Call Framework
4 //
5 // Copyright (c) 2005 - 2013, Delta V Software. All rights reserved.
6 // http://www.deltavsoft.com
7 //
8 // RCF is distributed under dual licenses - closed source or GPL.
9 // Consult your particular license for conditions of use.
10 //
11 // If you have not purchased a commercial license, you are using RCF
12 // under GPL terms.
13 //
14 // Version: 2.0
15 // Contact: support <at> deltavsoft.com
16 //
17 //******************************************************************************
18 
19 //
20 // detail/win_thread.hpp
21 // ~~~~~~~~~~~~~~~~~~~~~
22 //
23 // Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
24 //
25 // Distributed under the Boost Software License, Version 1.0. (See accompanying
26 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
27 //
28 
29 #ifndef RCF_DETAIL_WIN_THREAD_HPP
30 #define RCF_DETAIL_WIN_THREAD_HPP
31 
32 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
33 # pragma once
34 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
35 
36 #if defined(BOOST_WINDOWS) && !defined(UNDER_CE)
37 
38 #include <RCF/thread/push_options.hpp>
39 
40 namespace RCF {
41 namespace detail {
42 
43 RCF_EXPORT unsigned int __stdcall win_thread_function(void* arg);
44 
45 class func_base
46 {
47 public:
48  func_base() : entry_event_(0), exit_event_(0)
49  {}
50 
51  virtual ~func_base()
52  {
53  if (entry_event_)
54  {
55  ::CloseHandle(entry_event_);
56  entry_event_ = 0;
57  }
58  if (exit_event_)
59  {
60  ::CloseHandle(exit_event_);
61  exit_event_ = 0;
62  }
63  }
64 
65  virtual void run() = 0;
66 
67  ::HANDLE entry_event_;
68  ::HANDLE exit_event_;
69 };
70 
71 template <typename Function>
72 class func
73  : public func_base
74 {
75 public:
76  func(Function f)
77  : f_(f)
78  {
79  }
80 
81  virtual void run()
82  {
83  f_();
84  }
85 
86 private:
87  Function f_;
88 };
89 
90 class RCF_EXPORT win_thread
91  : private noncopyable
92 {
93 public:
94  // Constructor.
95  template <typename Function>
96  win_thread(Function f, unsigned int stack_size = 0)
97  : thread_(0)
98  {
99  mArgPtr.reset(new func<Function>(f));
100  start_thread(stack_size);
101  }
102 
103  // Destructor.
104  ~win_thread();
105 
106  // Wait for the thread to exit.
107  void join();
108 
109 private:
110  friend RCF_EXPORT unsigned int __stdcall win_thread_function(void* arg);
111 
112  void start_thread(unsigned int stack_size);
113 
114  ::HANDLE thread_;
115 
116  boost::shared_ptr<func_base> mArgPtr;
117 };
118 
119 } // namespace detail
120 } // namespace RCF
121 
122 #include <RCF/thread/pop_options.hpp>
123 
124 #endif // defined(BOOST_WINDOWS) && !defined(UNDER_CE)
125 
126 #endif // RCF_DETAIL_WIN_THREAD_HPP