Re: Pointer to member function
Thanks for that James,
James Kanze wrote:
int rc = pthread_create( &m_thread, NULL, m_main, (void *)args);
If this compiles, your compiler is broken.
And replacing m_main
with k_main shouldn't change anything here.
It works with g++.
You need a
separate free function:
extern "C" void*
threadStarter( void* args )
static_cast< CMyThread* >( args )->m_main() ;
As it worked, I hadn't really considered the difficulties that other
compilers might cause.
And since you're dealing with an object, you don't need the
additional args---they can just be member variables of the
Finally, of course, you can't call pthread_create from a
constructor of a base class without encuring race conditions; as
a general rule, you should never call it from the constructor of
a "thread" object which you expect run.
pthread_join( m_thread, NULL);
pthread_join can block. I'm not sure its a good idea to call it
from a destructor. (Destructors are called during stack
walkback, in case of an exception. Which is generally a context
where you don't want to block for an indefinite time.)
I'll have to think of a way of tidying up if exceptions are thrown.
The usual solution for this sort of thing is to separate the
thread from what it does. Not only does it work, but it's a lot
cleaner in the long run. Thus, you might end up with something
I had come up with something similar, but in reverse.
I had a virtual class Thread that the user derives from, which contained
an implementation class ThreadImp that is created when the thread is
I was still passing around void* arg lists without stopping to think
about whether I really needed to. (In the latest version I stored a void
* arg in the Thread class.
thanks for your suggestion.