// JP opened flex table

Click to See Complete Forum and Search --> : Is this way of writing thread correct?


chee0007
September 18th, 2007, 10:58 PM
Hi guys

From what i have learnt, a static function cannot reference to outside variables directly except variables that is declared inside the static function itself.

So by calling another function that actually do all the thread procedures, I can change and manipulate variables directly without using pointers and such.

But if i do that, will it cause any memory leaks or disadvantages?

see codes below...







static UINT __cdecl MyThreadStatic(void *p);
UINT MyThread();



UINT __cdecl MyClass::MyThreadStatic(void *p)
{
return ( ( (MyClass*) p ) ->MyThread() )
}

UINT MyClass::MyThread()
{
while(1)
{//do some stuff}

return 0;
}

Arjay
September 19th, 2007, 12:49 AM
While it will get the job done, you can just make the threadproc static and do away with the intermediate function.

For example, consider the following two methods of a CMyClass class (one a threadproc and the other used to create the thread).


HRESULT CreateThread( )
{
// Fire off the thread
if( NULL == ( m_hThread = (HANDLE)_beginthreadex(
NULL,
0,
ThreadProc,
static_cast<LPVOID>( this ),
0,
NULL)) )
{
return HRESULT_FROM_WIN32( ::GetLastError() );
}
return S_OK;
}

static UINT WINAPI ThreadProc( LPVOID lpContext )
{
// Turn the passed in 'this' pointer back into a CMyClass instance
CMyClass* pMyClass = reinterpret_cast< CMyClass* >( lpContext );

// Able to access MyClass data
// pMyClass

while(1)
{
// Check for exit
if( WAIT_OBJECT_0 == WaitForSingleObject( pMyClass->GetShutdownEvent( ), 0 ) )
{
return 1;
}

// Do more work
// ...
}
return 0;
}

//JP added flex table