add possibility to do things after thread start.. but before setting the thread to...
[vuplus_dvbapp] / 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->before_set_thread_alive();
19         p->alive=1;
20         pthread_cleanup_push( thread_completed, (void*)p );
21         p->thread();
22         pthread_exit(0);
23         pthread_cleanup_pop(1);
24         return 0;
25 }
26
27 eThread::eThread()
28         :the_thread(0), alive(0)
29 {
30 }
31
32 void eThread::run( int prio, int policy )
33 {
34         if (alive)
35         {
36                 eDebug("thread already running !!");
37                 return;
38         }
39         pthread_attr_t attr;
40         pthread_attr_init(&attr);
41         if (prio||policy)
42         {
43                 struct sched_param p;
44                 p.__sched_priority=prio;
45                 pthread_attr_setschedpolicy(&attr, policy );
46                 pthread_attr_setschedparam(&attr, &p);
47         }
48         if ( pthread_create(&the_thread, &attr, wrapper, this) )
49         {
50                 eDebug("couldn't create new thread");
51                 return;
52         }
53         pthread_attr_destroy(&attr);
54         usleep(1000);
55         int timeout=50;
56         while(!alive && timeout--)
57         {
58 //              eDebug("waiting for thread start...");
59                 usleep(1000*10);
60         }
61         if ( !timeout )
62                 eDebug("thread couldn't be started !!!");
63 }                     
64
65 eThread::~eThread()
66 {
67         kill();
68 }
69
70 void eThread::sendSignal(int sig)
71 {
72         if ( alive )
73                 pthread_kill( the_thread, sig );
74         else
75                 eDebug("send signal to non running thread");
76 }
77
78 void eThread::kill(bool sendcancel)
79 {
80         if (!the_thread)
81                 return;
82         if ( alive && sendcancel )
83         {
84                 eDebug("send cancel to thread");
85                 pthread_cancel(the_thread);
86         }
87         eDebug("thread joined %d", pthread_join(the_thread, 0));
88         the_thread=0;
89 }