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