small fix
[enigma2.git] / lib / base / thread.h
1 #ifndef __lib_base_thread_h
2 #define __lib_base_thread_h
3
4 #include <pthread.h>
5 #include <signal.h>
6 #include <lib/base/elock.h>
7
8 /* the following states are possible:
9  1 thread has not yet started
10  2 thread has started, but not completed initialization (hadStarted not yet called)
11  3 thread is running
12  4 thread has finished, but not yet joined
13  5 thread has joined (same as state 1)
14  
15  sync() will return:
16         0 (="not alive") for 1, 4, 5
17         1 for 3, 4
18         
19         it will wait when state is 2. It can't differentiate between
20         state 3 and 4, because a thread could always finish.
21         
22         all other state transitions (1 -> 2, 4 -> 5) must be activately
23         changed by either calling run() or kill().
24  */
25
26 class eThread
27 {
28 public:
29         eThread();
30         virtual ~eThread();
31
32                 /* thread_finished is called from within the thread context as the last function
33                    before the thread is going to die.
34                    It should be used to do final cleanups (unlock locked mutexes ....) */
35         virtual void thread_finished() {}
36
37                 /* runAsync starts the thread.
38                    it assumes that the thread is not running,
39                    i.e. sync() *must* return 0.
40                    it will not wait for anything. */
41         int runAsync(int prio=0, int policy=0);
42
43                 /* run will wait until the thread has either
44                    passed it's initialization, or it has
45                    died again. */
46         int run(int prio=0, int policy=0);
47
48         virtual void thread()=0;
49         
50                 /* waits until thread is in "run" state */
51                 /* result: 0 - thread is not alive
52                            1 - thread state unknown */
53         int sync();
54         int sendSignal(int sig);
55
56                 /* join the thread, i.e. busywait until thread has finnished. */
57         void kill(bool sendcancel=false);
58 private:
59         pthread_t the_thread;
60
61         static void *wrapper(void *ptr);
62         int m_alive;
63         static void thread_completed(void *p);
64
65         eSemaphore m_state;
66 protected:
67         void hasStarted();
68 };
69
70 #endif