how do i create a thread with a class function?

  • Thread starter Thread starter Chris LaJoie
  • Start date Start date
C

Chris LaJoie

The code below creates a thread on a global function (ReadChildOutput):

CreateThread(NULL, 0, ReadChildOutput, (LPVOID)this, 0, &ThreadId);

How would I create a thread on a non-global function, assuming the
ReadChildOutput function were in the current class. This code illustrates
what I mean, but does not compile.

CreateThread(NULL, 0, this->ReadChildOutput, NULL, 0, &ThreadId);

Thanks,
Chris
 
Chris said:
The code below creates a thread on a global function
(ReadChildOutput):

CreateThread(NULL, 0, ReadChildOutput, (LPVOID)this, 0, &ThreadId);

How would I create a thread on a non-global function, assuming the
ReadChildOutput function were in the current class. This code
illustrates what I mean, but does not compile.

CreateThread(NULL, 0, this->ReadChildOutput, NULL, 0, &ThreadId);

Thanks,
Chris

You have to use a "global" helper function. Pass the 'this' pointer as the
LPINFO parameter to CreateThread, and the address of the static function as
the start address. In the static function, cast the void* info into
CYourClass* and call the member function. From your example above, it looks
like you're already doing that.

-cd
 
Chris said:
The code below creates a thread on a global function (ReadChildOutput):

CreateThread(NULL, 0, ReadChildOutput, (LPVOID)this, 0, &ThreadId);

How would I create a thread on a non-global function, assuming the
ReadChildOutput function were in the current class. This code illustrates
what I mean, but does not compile.

CreateThread(NULL, 0, this->ReadChildOutput, NULL, 0, &ThreadId);
Chris

Briefly, the problem is that all class instance functions have an
implicit "this" as a first (hidden) argument. Thus it simply won't
compile or be the right shape!

/steveA
 
Back
Top