----------------- The class member function cannot be a thread function ---------------------------
Generally, C ++ class member functions cannot be used as thread functions. This is because the compiler adds a member function defined in the class
The above this pointer. See the following program:
# Include "windows. H"
# Include <process. h>
Class exampletask
{
Public:
Void taskmain (lpvoid PARAM );
Void starttask ();
};
Void exampletask: taskmain (lpvoid PARAM)
{}
Void exampletask: starttask ()
{
_ Beginthread (taskmain, 0, null );
}
Int main (INT argc, char * argv [])
{
Exampletask realtimetask;
Realtimetask. starttask ();
Return 0;
}
Compilation error:
Error c3867: 'exampletask: taskmain': function call Missing argument list; Use '& exampletask: taskmain' to create a pointer to membe
The following code displays the same compilation error.
# Include "windows. H"
# Include <process. h>
Class exampletask
{
Public:
Void taskmain (lpvoid PARAM );
};
Void exampletask: taskmain (lpvoid PARAM)
{}
Int main (INT argc, char * argv [])
{
Exampletask realtimetask;
_ Beginthread (exampletask: taskmain, 0, null );
Return 0;
}
If you must use a class member function as a thread function, there are usually the following solutions:
(1) Declare the member function as static type and remove the this pointer;
Change the class definition:
# Include "windows. H"
# Include <process. h>
Class exampletask
{
Public:
Void static taskmain (lpvoid PARAM );
Void starttask ();
};
Although declaring a member function as static can solve the problem of using it as a thread function, it brings about a new problem, that is, static
Member functions can only access static members. One way to solve this problem is to call this
The pointer is passed in as a parameter, and forced type conversion is used in the thread function to convert this to a pointer to this class.
Static member.
(2) do not define a class member function as a thread function, but define a thread function as a class member function. In this way, thread functions can also have classes
Member functions have the same permissions;
We changed the program:
# Include "windows. H"
# Include <process. h>
Class exampletask
{
Public:
Friend void taskmain (lpvoid PARAM );
Void starttask ();
Int value;
};
Void taskmain (lpvoid PARAM)
{
Exampletask * ptaskmain = (exampletask *) Param;
// Use the ptaskmain pointer to reference
}
Void exampletask: starttask ()
{
_ Beginthread (taskmain, 0, this );
}
Int main (INT argc, char * argv [])
{
Exampletask realtimetask;
Realtimetask. starttask ();
Return 0;
}