]> git.tdb.fi Git - libs/core.git/blob - source/core/thread.h
Use nullptr instead of 0 for pointers
[libs/core.git] / source / core / thread.h
1 #ifndef MSP_CORE_THREAD_H_
2 #define MSP_CORE_THREAD_H_
3
4 #include <string>
5 #include "noncopyable.h"
6
7 namespace Msp {
8
9 /**
10 Base class for threads.  To create a thread for some task, derive it from this
11 class and implement the main() function.  Note that threads are not
12 automatically started upon creation - you must manually call launch() instead.
13 This is to allow initializing variables of the derived class before the thread
14 is started.
15 */
16 class Thread: private NonCopyable
17 {
18 private:
19         struct Private;
20
21         enum State
22         {
23                 PENDING,
24                 RUNNING,
25                 FINISHED,
26                 KILLED,
27                 JOINED
28         };
29
30         Private *_priv = nullptr;
31         std::string _name;
32         State _state = PENDING;
33
34 protected:
35         Thread(const std::string & = std::string());
36 public:
37         virtual ~Thread();
38
39         const std::string &get_name() const { return _name; }
40
41         /** Indicates whether the thread has finished running. */
42         bool is_finished() { return _state>=FINISHED; }
43
44         /** Waits for the thread to exit.  Calling this from the thread will cause a
45         deadlock. */
46         void join();
47
48         /** Violently terminates the thread.  This should only be used as a last
49         resort, as the thread gets no chance to clean up. */
50         void kill();
51
52 protected:
53         /** Starts the thread.  Can only be called once for each Thread instance. */
54         void launch();
55
56 private:
57         void platform_join();
58         void platform_kill();
59         void platform_launch();
60         void platform_setname();
61
62 protected:
63         virtual void main() = 0;
64 };
65
66 } // namespace Msp
67
68 #endif