Skip to content

Instantly share code, notes, and snippets.

@mastbaum
Created January 24, 2012 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mastbaum/1668149 to your computer and use it in GitHub Desktop.
Save mastbaum/1668149 to your computer and use it in GitHub Desktop.
member function pointers with special function
#include <iostream>
#include <pthread.h>
/** Member function pointers given function name */
// class Launcher exists as a container of an instance and an argument.
// Using templates allows us to use the Launcher for a member of any class
template <class T>
class Launcher {
public:
Launcher(T* _o, void* _arg) : o(_o), arg(_arg) {}
void* launch() { return (o->threadMe)(arg); }
T* o;
void* arg;
};
// a function with happily external linkage, which we will pass to
// pthread_create instead of the (internal) member function
template <class T>
void* LaunchMember(void* o) {
Launcher<T>* l = reinterpret_cast<Launcher<T>* >(o);
return l->launch();
}
class Bar {
public:
Bar() : i(0) {}
int i;
};
class Foo {
public:
Foo();
void* threadMe(void* arg);
private:
pthread_t fThread;
Bar bar;
};
Foo::Foo() {
bar.i = 42;
int arg = 12;
Launcher<Foo> l(this, (void*)&arg);
pthread_create(&fThread, NULL, LaunchMember<Foo>, &l);
pthread_join(fThread, NULL);
}
void* Foo::threadMe(void* arg) {
std::cout << "Foo::threadMe: *arg = " << *((int*)(arg)) << std::endl;
std::cout << "Foo::threadMe: bar.i = " << bar.i << std::endl;
}
int main(int argc, char* argv[]) {
Foo* f = new Foo();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment