Visual C++ CreateThread Parameter Problem
I have a class that contains a function that calls create thread, and needs to pass itself (this) as a parameter:
DWORD threadId;
HANDLE h = CreateThread( NULL, 0, runThread, this开发者_JAVA百科, 0, &threadId);
My runThread definition is as follows:
DWORD WINAPI runThread(LPVOID args)
{
Obj *t = (Obj*)args;
t->funct();
return 0;
}
Unfortunately, the object t that I get in runThread() gets garbage. My Obj class has a function pointer attribute. Could that be the problem?
class Obj{
void(*funct)();
and in the constructor:
Obj(void(*f)())
{
funct = f;
}
where is my mistake? The function pointer, the createThread itself, or type-casting? I tried whatever I could think of.
Assuming the object has been properly constructed, is there any chance that the object that is creating the thread has gone out of scope after CreateThread is called? This would leave your thread with a garbage object. If not, single step through the code with a debugger, and have a look at the objects 'this' pointer as the thread is being called, with a breakpoint at the thread start to see what it is getting as parameters.
The object was created in my main thread of execution. The error was because the object was going out of scope two lines down in that thread, so when the thread executed there was only garbage at the address.
精彩评论