thread_util.h 1.66 KB
Newer Older
Sam Moore's avatar
Sam Moore committed
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#ifndef THREAD_UTIL_H
#define THREAD_UTIL_H

#include <stdlib.h>
#include <stdio.h>

#include <sstream>
#include <string>
#include <pthread.h> //Needed for threading
#include <signal.h> //Needed for killing the threads (why not in pthread.h?)

#include <assert.h>


class Thread
{
	public:
		Thread() : finished(false), thread(0),  started(false)
		{
			
		}

		virtual void Start() = 0;
	protected:
		void Start(void* (ThreadFunction)(void*))
		{
			assert(!started);
			started = true;
			pthread_create(&(thread), NULL, ThreadFunction, (void*)(this));
			pthread_setcancelstate(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
		}

	public:
		void Stop()
		{
			assert(started);
			if (!finished)
				pthread_cancel(thread);
			
			pthread_join(thread, NULL);
			started = false;
		}

		virtual ~Thread()
		{
			if (started)
				Stop();
		}

		bool Finished() const {return finished;}
	protected:
		
		bool finished;

	private:
		pthread_t thread;
	protected:
		bool started;
};

class GetterThread : public Thread
{
	public:
		GetterThread(FILE * newStream, std::string & newBuffer) : Thread(), stream(newStream), buffer(newBuffer)
		{
			
		}

		virtual ~GetterThread()
		{

		}

		virtual void Start() {assert(&buffer != NULL); Thread::Start(GetMessage);}

	private:
		FILE * stream;
	public:
		std::string & buffer;

		pthread_t thread;
		static pthread_mutex_t mutex;
		static void * GetMessage(void * p);

};


class TimerThread : public Thread
{
	public:
		TimerThread(int newCount) : Thread(), count(newCount)
		{
			
		}

		virtual ~TimerThread()
		{

		}

		virtual void Start() {Thread::Start(Timeout);}

	private:
		int count;

		static void * Timeout(void * p);

};

#endif //THREAD_UTIL_H

//EOF