Monday, July 23, 2007

C++: A nice thread class

Java and .Net have very nice and easy ways to create threads. We can trun any class into a thread within seconds and that's probably one of their coolest features. As a Win32 C++ programmer, we don't have this advantage. But we can achieve this very easily. Here is how.

Following is my thread class which you need to include to make threading a piece of cake.

The class:
  1 class Thread
2
{
3
public:
4
Thread()
5
{
6
hThread = 0;
7
}
8
9
void start()
10
{
11
_threadObj = this;
12
13
DWORD threadID;
14
hThread = CreateThread(0, 0, threadProc, _threadObj, 0, &threadID);
15
}
16
17
void stop()
18
{
19
if (hThread)
20
TerminateThread (hThread, 0);
21
}
22
23
virtual void run() = 0;
24
25
protected:
26
static unsigned long __stdcall threadProc(void* ptr)
27
{
28
((Thread*)ptr)->run();
29
return 0;
30
}
31
32
Thread *_threadObj;
33
HANDLE hThread;
34
};
35

Example of usages:
 36 class YourClass: public Thread
37
{
38
public:
39
YourClass() { }
40
~YourClass() { }
41
42
//the run function, you need to override this one
43
void run();
44
45
private:
46
//private variables
47
};
48
49
void YourClass::run()
50
{
51
//Add your threaded code here
52
}
53
54
int main()
55
{
56
YourClass obj;
57
obj.start();
58
59
//the thread is running
60
61
obj.stop();
62
63
//the thread is stopped
64
return 0;
65
}
66


Looks cool, right? It's your turn to try it. Happy threading.