Tuesday, March 11, 2008

C++ Threading

Simple way to create thread...
CreateThread()

The thread function is derived from DWORD WINAPI
Suppose the C++ class name is MyClass and we have to implement a thread for Myfunction().

In "MyClass.h" declare and implement the following
////////////////***********************************************/////////////////////
class MyClass
{
private:
HANDLE m_hThread;

void MyFunction() ;
static DWORD WINAPI MyFunctionThreadEntry( IN LPVOID pv)
{
((MyClass*) pv) ->MyFunction() ;
return EXIT_SUCCESS ;
}

MyClass()
{
m_hThread=NULL;
}
/// do other initializations
}
////////////////***********************************************/////////////////////

In "MyClass.cpp" implement the following
////////////////***********************************************/////////////////////
void MyClass::MyFunction()
{
///Add function code
}
////////////////***********************************************/////////////////////

How the thread is invoked?
Call CreateThread to invoke thread function.

DWORD dw=0;
m_hThread=CreateThread (NULL,NULL, (LPTHREAD_START_ROUTINE) MyClass::MyFunctionThreadEntry,
this,
NULL,
& dw
) ;

No comments:

Post a Comment