Click to See Complete Forum and Search --> : CreateThread and Winsock Question


jamesbr
November 24th, 2002, 07:25 AM
I was looking at the Winsock FAQ (http://tangentsoft.net/wskfaq/) and they had an example for a simple multi threaded server. I complied it and it worked fine. I then made a new project and made a threaded server class, CServer. When I compiled it the line

CreateThread(0, 0, EchoHandler, (void*)sd, 0, &nThreadID);

generated the error

error C2664: 'CreateThread' : cannot convert parameter 3 from 'unsigned long (void *)' to 'unsigned long (__stdcall *)(void *)'
None of the functions with this name in scope match the target type


the prototype for the function is
DWORD WINAPI CServer::EchoHandler(void* sd_)

its the exact same as in the example except for the 'CServer::' does anyone have any ideas why this won't work? Thanks in advance
James

j0nas
November 24th, 2002, 07:41 AM
You can't pass a C++ method to CreateThread. You need to do something like this:

void CServer::Something()
{
...
CreateThread(0, 0, ::EchoHandler, (void*)this, 0, &nThreadID);
...
}

DWORD WINAPI CServer::EchoHandler()
{
// do your stuff here
}


// Wrapper function
DWORD WINAPI EchoHandler(void *classPtr)
{
CServer *server = (CServer *)classPtr;

return server->EchoHandler();
}

kuphryn
November 24th, 2002, 10:54 AM
There are several solution. Before we explore one solution, I recommend that you use _beginthreadex() instead of CreateThread(). _beginthreadex() from C/C++ run-time library cleans up memory after you use any functions from the library.

Here is one solution.


unsigned _stdcall CServer::EchoHandler();

struct EchoParam
{
// Whatever you want to pass in the callback function.
};

DWORD threadID = 0;
EchoParam *ptp = new EchoParam;
...

HANDLE hThread = reinterpret_cast<HANDLE>(
_beginthreadex(// Default security
NULL,
0,
// Callback function
EchoHandler,
// Callback function paramater.
reinterpret_cast<void *>(ptp),
// Initial flags
0,
// Thread ID
&threadID));


Kuphryn

Andreas Masur
November 24th, 2002, 01:05 PM
Originally posted by jamesbr
CreateThread(0, 0, EchoHandler, (void*)sd, 0, &nThreadID);

generated the error

error C2664: 'CreateThread' : cannot convert parameter 3 from 'unsigned long (void *)' to 'unsigned long (__stdcall *)(void *)'
None of the functions with this name in scope match the target type

It looks like 'EchoHandler()' is a member function of your class. In this case it needs to be static in order to be used as a thread function. Further explanation can be found in the FAQ (http://www.codeguru.com/FAQS/#803)...