Utilities
Utilities header only library
ClrThreadHolder.h
1 /*
2  Copyright (C) Skeletex Research, s.r.o. - All Rights Reserved
3  Unauthorized copying of this file, via any medium is strictly prohibited
4  Proprietary and confidential
5 */
6 #ifndef UTILS_CLR_THREAD_HOLDER_H
7 #define UTILS_CLR_THREAD_HOLDER_H
8 #ifdef _WIN32
9 #include <windows.h>
10 #include <process.h>
11 #include <functional>
12 
13 namespace utils
14 {
15 
17  class ClrThreadHolder
18  {
19  public:
20 
22  ClrThreadHolder() = default;
23 
25  void SetFuncLoop(std::function<void(void)> _func)
26  {
27  isLoopFunc = true;
28  pFunc = _func;
29  };
30 
32  void SetFunc(std::function<void(void)> _func)
33  {
34  isLoopFunc = false;
35  pFunc = _func;
36  };
37 
39  void Start()
40  {
41  hThread = (HANDLE)_beginthreadex(0, 0, &ClrThreadHolder::func_wrapper, static_cast<void *>(this), 0, 0);
42  };
43 
45  bool IsRunning() const
46  {
47  return isRunning;
48  };
49 
51  void SyncStop()
52  {
53  isStopRequested = true;
54 
55  // actually wait for the thread to exit
56  WaitForSingleObject(hThread, INFINITE);
57 
58  // get the thread's exit code
59  DWORD exitcode;
60  GetExitCodeThread(hThread, &exitcode);
61 
62  // cleanup the thread.
63  CloseHandle(hThread);
64  hThread = nullptr;
65  };
66 
68  ~ClrThreadHolder() {};
69 
70  private:
71 
72  unsigned int iThreadID = 0;
73  HANDLE hThread = nullptr;
74 
75  std::function<void(void)> pFunc = nullptr;
76  bool isLoopFunc = false;
77  bool isStopRequested = false;
78  bool isRunning = false;
79 
80  // Main thread function.
81  unsigned MyThreadFunc()
82  {
83  if (pFunc == nullptr) { return 1; }
84  isRunning = true;
85  do { pFunc(); }
86  while (isLoopFunc && !isStopRequested);
87  isRunning = false;
88  return 0;
89  }
90 
91  // Thread cast compatibility function.
92  static unsigned __stdcall func_wrapper(void *o)
93  {
94  return static_cast<ClrThreadHolder *>(o)->MyThreadFunc();
95  }
96  };
97 
98 }
99 
100 #endif
101 #endif /* !UTILS_CLR_THREAD_HOLDER_H */
General namespace for utilities.
Definition: BulletConversions.h:9