Phasor  01.00.10.059
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Threads.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include "Types.h"
4 
5 class Lock
6 {
7 private:
8  CRITICAL_SECTION& cs;
9 public:
10  Lock(CRITICAL_SECTION& cs);
11  ~Lock();
12 };
13 
14 class TryLock
15 {
16 private:
17  CRITICAL_SECTION& cs;
18  bool locked;
19 public:
20  TryLock(CRITICAL_SECTION& cs);
21  bool obtained() const;
22  ~TryLock();
23 };
24 
25 class Thread
26 {
27 protected:
28 
29  // The created thread must call this when it's initialized, otherwise
30  // it will be terminated.
31  void ready();
32 
33  // An error occurred during initialization, the thread should terminate.
34  void error();
35 
36  // Check if the thread should continue running (true - yes, false - no)
37  bool check(DWORD dwSleep = 0);
38 
39 private:
40  HANDLE h_thread, h_createEvent, h_syncEvent;
41  volatile bool success;
42 
43  // Called when the thread is created (from that thread)
44  static DWORD WINAPI created(LPVOID data);
45 
46  void CleanupHandle(HANDLE& handle);
47  bool ForceCleanup();
48 
49 public:
50  Thread();
51  virtual ~Thread();
52 
53  // Create the thread and call thread_main
54  virtual bool run();
55 
56  // Notify the thread that it should close.
57  void close();
58 
59  // Checks if the thread has finished
60  bool has_closed();
61 
62  // This is the entry point of the thread, gets called after run.
63  // This function must call ready once initialized, otherwise it will
64  // be aborted.
65  // The class implementing this function is always responsible for polling
66  // running to check when it should be closed.
67  virtual int thread_main() = 0;
68 
69  // Example thread_main
70  // int thread_main()
71  // {
72  // try
73  // {
74  // // setup event queues and the like
75  // }
76  // catch (...)
77  // {
78  // error();
79  // return 1;
80  // }
81  //
82  // ready();
83  //
84  // while (check())
85  // {
86  //
87  // }
88  //
89  // return 0;
90  // }
91 
92 };