try to fix some eThread races
[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                 /* runAsync starts the thread.
33                    it assumes that the thread is not running,
34                    i.e. sync() *must* return 0.
35                    it will not wait for anything. */
36         int runAsync(int prio=0, int policy=0);
37
38                 /* run will wait until the thread has either
39                    passed it's initialization, or it has
40                    died again. */
41         int run(int prio=0, int policy=0);
42
43         virtual void thread()=0;
44         
45                 /* waits until thread is in "run" state */
46                 /* result: 0 - thread is not alive
47                            1 - thread state unknown */
48         int sync();
49         void sendSignal(int sig);
50
51                 /* join the thread, i.e. busywait until thread has finnished. */
52         void kill(bool sendcancel=false);
53 private:
54         pthread_t the_thread;
55
56         static void *wrapper(void *ptr);
57         int m_alive;
58         static void thread_completed(void *p);
59
60         eSemaphore m_state;
61 protected:
62         void hasStarted();
63 };
64
65 #endif