Wednesday, January 30, 2008

Use _beginthread/_beginthreadex instead CreateThread.



According to Jeffrey's book(Windows via C/C++) , When using CRT function/library(_fcvt, errno, atof, etc) in thread procedure, we should use _beginthread/_beginthreadex.

Because, _beginthread/_beginthreadex allocate memory area for CRT .
However CreateThread does not has any method for CRT.
So It makes an unpredicted quit and memory leaks.

I've tested CreateThread and _beginthread/_beginthreadex.
Below code is tested code.
Project was Consol Project and used Purify Plus for detect memory leaks.






DWORD WINAPI ThreadProc(__in LPVOID lpParameter);

DWORD WINAPI InputProc(__in LPVOID lpParameter);

unsigned _stdcall CallThreadHandlerProc(void *pThreadHandler);

unsigned _stdcall InputProc_BT(void *pThreadHandler);

BOOL bExit = FALSE;
HANDLE ThrdHandle=0;
HANDLE InputThrd = 0;
DWORD thrdID;

int _tmain(int argc, _TCHAR* argv[])
{

unsigned int ID1, ID2;

/**
Thread Creation using CreateThread

uncomment
these lines test for CreateThread


ThrdHandle = CreateThread(0,0, ThreadProc, 0, 0,
&thrdID);

InputThrd =
CreateThread(0,0, InputProc, 0, 0, &thrdID);


**/


/*Thread Creation using
_beginthreadex*/

ThrdHandle = reinterpret_cast(_beginthreadex0,1024,

CallThreadHandlerProc,0,0,&ID1));


InputThrd = reinterpret_cast(_beginthreadex(0,1024,

InputProc_BT,0,0, &ID2));


WaitForSingleObject(ThrdHandle,
INFINITE);

CloseHandle(ThrdHandle);
CloseHandle(InputThrd);

return 0;

}


DWORD WINAPI ThreadProc(__in LPVOID lpParameter)

{

while (bExit == FALSE)

{

int decimal, sign;

char *buffer;

double source = 3.1415926535;

buffer = _fcvt( source, 7, &decimal, &sign );


}

return 0;

}


DWORD WINAPI InputProc(__in LPVOID lpParameter)

{

char ch;

std::cin>>ch;

bExit = TRUE;

return 0;

}


unsigned _stdcall CallThreadHandlerProc(void *pThreadHandler)

{

while (bExit == FALSE)

{

int decimal, sign;

char *buffer;

double source = 3.1415926535;
buffer = _fcvt( source, 7, &decimal, &sign );

}

DWORD exitCode;

GetExitCodeThread(ThrdHandle, &exitCode);

_endthreadex(exitCode);

return 0;

}

unsigned _stdcall InputProc_BT(void *pThreadHandler)

{

char ch;

std::cin>>ch;

bExit = TRUE;

DWORD exitCode;

GetExitCodeThread(InputThrd, &exitCode);

_endthreadex(exitCode);

return 0;

}




Result is CreateThread occured memory leaks.
This capture shows memory leaks at using _fcvt CRT function.


Below capture shows no memory leaks when using _beginthreadex.

No comments:

Powered By Blogger