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