You've come to this page because you've said something similar to the following:
I want to use a class function member as a thread function.
This is the Frequently Given Answer to such statements.
What you are trying to do is, simply, wrong. Thread functions may not be function members of classes. There is a conflict in the calling conventions. Use a function that is not a class member as the thread function. Make it call the class function member that you want to call in the thread.
The reason that what you are trying to do is wrong is obvious in the case of
non-static function members. The this
pointer required to be
passed as an implicit argument to the function is not passed as part of a
call to a thread function. At best, the calling convention for non-static
function members involves passing the this
pointer in a
register, and the function member will receive some entirely unrelated
value, which may or may not be a valid pointer, as its this
pointer. If the calling convention for non-static function members involves
passing the this
pointer on the stack, the function will
receive a stack frame of the wrong size and will probably fail with a
machine exception.
In the case of static function members, the reason that what you are trying
to do is wrong is actually the same, although this is not so obvious to
those that are not familiar with the C++ language. The linkage of a static
function member is different to the linkage of a thread function. Thread
creation routines such as pthread_create()
and
_beginthread()
expect a function with "C" linkage, whereas
class function members have "C++" linkage. On several C++ implementations,
functions with "C" linkage actually use a different calling convention to
functions with "C++" linkage, and so the program breaks.
Sometimes one can get away with using static function members as thread functions, even though it is wrong, because it just so happens that by default the same calling convention is used for both "C" and "C++" linkage. But one cannot always get away with this. For example: If one is using IBM VisualAge C++ and one is supplying the -Mt, the -Mc, or the -Ms option to the compiler, the calling convention for "C" linkage is different to the calling convention for "C++" linkage, and using a static function member as a thread function won't work.