Created
January 24, 2012 05:21
-
-
Save mastbaum/1668149 to your computer and use it in GitHub Desktop.
member function pointers with special function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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