• Advertisement
Sign in to follow this  

Need help to solve this passing member function pointer

This topic is 2511 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I can't use boost. So with that in mind. I have a class called Thread like so :

class Thread{
public:
typedef void*(*StartRoutine)(void*);
private:
pthread_t _thread;
public:
Thread(){}
void start(const StartRoutine initFunc, void* arg){
pthread_create(&_thread,NULL,initFunc,arg);
}
void waitToEnd(){
pthread_join(_thread,NULL);
}

};


and I want to call the start() function like so :

void startRequesting(){
_thread.start(&(this->_run), NULL );
}
private:
void* _run(void* arg){
while(!_jobs.empty()){
_scheduler->addJob( _jobs.front()); //ask for job request
_jobs.erase(_jobs.begin()); //remove that job after put into the buffer
}
return arg;
}


but that doesn't work. What option do I have?

Share this post


Link to post
Share on other sites
Advertisement
You need a trampoline function. A namespace-level or static member function that calls your regular member function.

static void trampoline(void* arg)
{
Runner* runner = static_cast<Runner*>(arg);
runner->run();
}

// here's your code, modified
void startRequesting()
{
_thread.start(trampoline, this);
}

Share this post


Link to post
Share on other sites

wow sweet. Nice wrapper idea. Is it really called a trampoline function?


"Wrapper", "adapter", and other names exist.

Share this post


Link to post
Share on other sites
Just a side note:
Don't use variable names like _foobar or foobar_.
Names with _ on front of the var or at the end are reserved to the compiler.
And yes, this solution is perfectly portable.
You can use this approach whenever a userpointer can be passed to a C-Callback. This way you can also wrap WinProc etc in Windows.
Another solution can be to use boost::bind to bind a member-function directly, or std::tr1::bind which is the same but needs support for C++0x TR1 in your compiler.

Share this post


Link to post
Share on other sites

Names with _ on front of the var or at the end are reserved to the compiler. [/quote]
Incorrect.

Trailing underscores are never reserved.

Beginning underscores are more complex. Anything beginning with two underscores or an underscore and an uppercare letter is reserved. Globally scoped names beginning with an underscore are reserved for the compiler.

But I agree in principle, the decoration is unnecessary.

Share this post


Link to post
Share on other sites
Can you show me the solution with bind function? I was thinking of that line but wasn't able to get it to work.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement