Subversion Repositories HomeAutomation

Rev

Go to most recent revision | Details | Last modification | View Log | SVN | RSS feed

Rev Author Line No. Line
969 runge 1
/***************************************************************************
2
 *   Copyright (C) November 29, 2008 by Mattias Runge                             *
3
 *   mattias@runge.se                                                      *
4
 *   thread.h                                            *
5
 *                                                                         *
6
 *   This program is free software; you can redistribute it and/or modify  *
7
 *   it under the terms of the GNU General Public License as published by  *
8
 *   the Free Software Foundation; either version 2 of the License, or     *
9
 *   (at your option) any later version.                                   *
10
 *                                                                         *
11
 *   This program is distributed in the hope that it will be useful,       *
12
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14
 *   GNU General Public License for more details.                          *
15
 *                                                                         *
16
 *   You should have received a copy of the GNU General Public License     *
17
 *   along with this program; if not, write to the                         *
18
 *   Free Software Foundation, Inc.,                                       *
19
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
20
 ***************************************************************************/
21
 
22
#ifndef _THREAD_H
23
#define	_THREAD_H
24
 
25
#include <pthread.h>
26
 
27
template <class T>
28
class Thread
29
{
30
public:
31
	Thread()
32
	{
33
		myIsCreated = false;
34
		myError = 0;
35
	};
36
	~Thread()
37
	{
38
		stop();
39
	};
40
 
41
	bool stop()
42
	{
43
		if (!myIsCreated)
44
			return true;
45
 
46
		myError = pthread_cancel(myHandle);
983 runge 47
		join();
969 runge 48
		myIsCreated = false;
49
 
50
		return myError == 0;
51
	};
52
	bool start()
53
	{
54
		myError = pthread_create(&myHandle, NULL, T::doThread, (void*)this);
55
 
56
		if (myError != 0)
57
		{
58
			myIsCreated = false;
59
			return false;
60
		}
61
 
62
		myIsCreated = true;
63
		return true;
64
	};
65
	bool join()
66
	{
67
		if (!myIsCreated)
68
			return false;
69
 
70
		myError = pthread_join(myHandle, NULL);
71
 
72
		if (myError != 0)
73
		{
74
			myIsCreated = false;
75
			return false;
76
		}
77
 
78
		myIsCreated = true;
79
		return true;
80
	};
81
	int getError()
82
	{
83
		return myError;
84
	};
85
 
86
	static void *doThread(void* ptr)
87
	{
88
		((T*)ptr)->run();
89
	};
90
	void run() { };
91
 
92
private:
93
	bool myIsCreated;
94
	pthread_t myHandle;
95
	int myError;
96
};
97
 
98
#endif	/* _THREAD_H */
99