summaryrefslogtreecommitdiff
path: root/src/thread.cpp
blob: f4924c0a308cbcd2a625f507cea1a09711c71ad9 (plain) (blame)
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
#include <thread.h>
#include <exception.h>
#include <logger.h>

namespace newsbeuter {

/*
 * The thread class is a wrapper around the pthread functions found on virtually
 * all modern Unix systems.
 *
 * To run a thread, you need to derive your own class from thread and implement the
 * run() method. Then you create an instance of your derived class with the new
 * operator (very important!), and run the start() method of the object. 
 */


thread::thread() {
}

thread::~thread() { 

}

pthread_t thread::start() {
	int rc = pthread_create(&pt, 0, run_thread, this);
	LOG(LOG_DEBUG, "thread::start: created new thread %d rc = %d", pt, rc);
	if (rc != 0) {
		throw exception(rc);
	}
	return pt;
}

void thread::join() {
	pthread_join(pt, NULL);
}

void thread::detach() {
	LOG(LOG_DEBUG, "thread::detach: detaching thread %d", pt);
	pthread_detach(pt);
}

void * run_thread(void * p) {
	thread * t = reinterpret_cast<thread *>(p);
	LOG(LOG_DEBUG, "run_thread: p = %p", p);
	t->run();
	delete t;
	return 0;
}

void thread::cleanup(thread * p) {
	delete p;
}

}