aboutsummaryrefslogtreecommitdiff
path: root/lib/base/thread.cpp
blob: fa09691a37162be4f7d664edef7142d5186ca99c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <lib/base/thread.h>

#include <stdio.h>
#include <unistd.h>
#include <lib/base/eerror.h>

void eThread::thread_completed(void *ptr)
{
	eThread *p = (eThread*) ptr;
	eDebug("thread has completed..");
	p->alive=0;
	p->thread_finished();
}

void *eThread::wrapper(void *ptr)
{
	eThread *p = (eThread*)ptr;
	p->alive=1;
	pthread_cleanup_push( thread_completed, (void*)p );
	p->thread();
	pthread_exit(0);
	pthread_cleanup_pop(0);
}

eThread::eThread()
	:alive(0)
{
}

void eThread::run( int prio, int policy )
{
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	if (prio||policy)
	{
		struct sched_param p;
		p.__sched_priority=prio;
		pthread_attr_setschedpolicy(&attr, policy );
		pthread_attr_setschedparam(&attr, &p);
	}
	pthread_create(&the_thread, &attr, wrapper, this);
	usleep(1000);
	int timeout=20;
	while(!alive && timeout--)
	{
		eDebug("waiting for thread start...");
		usleep(1000*10);
	}
	if ( !timeout )
		eDebug("thread couldn't be started !!!");
}                     

eThread::~eThread()
{
	if ( alive )
		kill();
}

void eThread::sendSignal(int sig)
{
	if ( alive )
		pthread_kill( the_thread, sig );
	else 
		eDebug("send signal to non running thread");
}

void eThread::kill(bool hard)
{
	if ( !alive )
	{
		eDebug("kill.. but thread don't running");
		return;
	}

	if ( hard )
	{
		eDebug("killing the thread...");
		pthread_cancel(the_thread);
		alive=0;
	}
	else
	{
		eDebug("waiting for thread shutdown...");
		pthread_join(the_thread, 0);
		eDebug("ok");
	}
}