1 #ifndef THREADCONTEXT_H
2 #define THREADCONTEXT_H
3 
4 #include "ptmutex.h"
5 
6 enum ThreadState {THREAD_IDLE,THREAD_STARTED,THREAD_RUNNING,THREAD_FINISHED,THREAD_CANCELLED};
7 class Thread;
8 
9 
10 class ThreadCondition : public PTMutex
11 {
12 	public:
13 	ThreadCondition();
14 	~ThreadCondition();
15 	virtual void Broadcast();		// Sends the signal - Mutex should be obtained first and released afterwards
16 	virtual void WaitCondition();	// Waits for the signal - mutex should be obtained first and released afterwards
17 	protected:
18 	pthread_cond_t cond;
19 };
20 
21 
22 // Demonstrates how to use the ThreadCondition - used to sync between subthread and main thread.
23 class ThreadSync : public ThreadCondition
24 {
25 	public:
ThreadSync()26 	ThreadSync() : ThreadCondition(), received(false)
27 	{
28 	}
~ThreadSync()29 	~ThreadSync()
30 	{
31 	}
Broadcast()32 	virtual void Broadcast()
33 	{
34 		ObtainMutex();
35 		ThreadCondition::Broadcast();
36 		received=true;
37 		ReleaseMutex();
38 	}
WaitCondition()39 	virtual void WaitCondition()
40 	{
41 		ObtainMutex();
42 		if(!received)
43 			ThreadCondition::WaitCondition();
44 		received=false;
45 		ReleaseMutex();
46 	}
47 	protected:
48 	bool received;
49 };
50 
51 
52 
53 #ifdef WIN32
54 typedef void *ThreadID;
55 #else
56 typedef pthread_t ThreadID;
57 #endif
58 
59 class ThreadFunction;
60 class Thread
61 {
62 	public:
63 	Thread(ThreadFunction *threadfunc);
64 	Thread();
65 	~Thread();
66 	void Stop();
67 	void Start();
68 	void WaitSync();	// Safe to use bi-directionally.
69 	int WaitFinished();
70 	int GetReturnCode();
71 	bool TestFinished();
72 	// Methods to be used from within threads
73 	void SendSync();	// Safe to use bi-directionally.
74 	bool TestBreak();
75 	// Static function - can be called anywhere
76 	static ThreadID GetThreadID();
77 	protected:
78 	static void *LaunchStub(void *ud);
79 	ThreadFunction *threadfunc;
80 	pthread_t thread;
81 	ThreadSync cond1;	// We use one cond for main thread -> subthread signalling...
82 	ThreadSync cond2;	// ...and another for subthread -> main thread signalling.
83 	pthread_attr_t attr;
84 	// This mutex is held all the time the thread's running.
85 	PTMutex threadmutex;
86 	int returncode;
87 	enum ThreadState state;
88 	ThreadID subthreadid;
89 };
90 
91 
92 // Base class for thread function.  Subclass this and override Entry with your own subthread code.
93 class ThreadFunction
94 {
95 	public:
ThreadFunction()96 	ThreadFunction()
97 	{
98 	}
~ThreadFunction()99 	virtual ~ThreadFunction()
100 	{
101 	}
Entry(Thread & t)102 	virtual int Entry(Thread &t)
103 	{
104 		t.SendSync();
105 		return(0);
106 	}
107 	protected:
108 };
109 
110 
111 #endif
112 
113