add missing files, add ability to specify table_id mask and table_id ext mask
[enigma2.git] / lib / base / thread.cpp
1 #include <lib/base/thread.h>
2
3 #include <stdio.h>
4 #include <unistd.h>
5 #include <lib/base/eerror.h>
6
7 void eThread::thread_completed(void *ptr)
8 {
9         eThread *p = (eThread*) ptr;
10         eDebug("thread has completed..");
11         p->alive=0;
12         p->thread_finished();
13 }
14
15 void *eThread::wrapper(void *ptr)
16 {
17         eThread *p = (eThread*)ptr;
18         p->alive=1;
19         pthread_cleanup_push( thread_completed, (void*)p );
20         p->thread();
21         pthread_exit(0);
22         pthread_cleanup_pop(0);
23 }
24
25 eThread::eThread()
26         :alive(0)
27 {
28 }
29
30 void eThread::run( int prio, int policy )
31 {
32         pthread_attr_t attr;
33         pthread_attr_init(&attr);
34         if (prio||policy)
35         {
36                 struct sched_param p;
37                 p.__sched_priority=prio;
38                 pthread_attr_setschedpolicy(&attr, policy );
39                 pthread_attr_setschedparam(&attr, &p);
40         }
41         pthread_create(&the_thread, &attr, wrapper, this);
42         usleep(1000);
43         int timeout=20;
44         while(!alive && timeout--)
45         {
46                 eDebug("waiting for thread start...");
47                 usleep(1000*10);
48         }
49         if ( !timeout )
50                 eDebug("thread couldn't be started !!!");
51 }                     
52
53 eThread::~eThread()
54 {
55         if ( alive )
56                 kill();
57 }
58
59 void eThread::sendSignal(int sig)
60 {
61         if ( alive )
62                 pthread_kill( the_thread, sig );
63         else 
64                 eDebug("send signal to non running thread");
65 }
66
67 void eThread::kill(bool hard)
68 {
69         if ( !alive )
70         {
71                 eDebug("kill.. but thread don't running");
72                 return;
73         }
74
75         if ( hard )
76         {
77                 eDebug("killing the thread...");
78                 pthread_cancel(the_thread);
79                 alive=0;
80         }
81         else
82         {
83                 eDebug("waiting for thread shutdown...");
84                 pthread_join(the_thread, 0);
85                 eDebug("ok");
86         }
87 }