Skip to content

Instantly share code, notes, and snippets.

@melvyniandrag
Created November 1, 2017 17:08
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 melvyniandrag/b9ac21a54fa938ca2e6e94953fc9aca2 to your computer and use it in GitHub Desktop.
Save melvyniandrag/b9ac21a54fa938ca2e6e94953fc9aca2 to your computer and use it in GitHub Desktop.
function ptrs to member functions and pthreads with member functions.
#include <unistd.h>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <pthread.h>
class Base{
public:
int x;
Base(int x_): x(x_){}
virtual ~Base(){}
void *myFunc( void * )
{
int N = 10000000;
for ( int i = 0; i < N; ++i )
{
++x;
}
}
};
int main(int argc, char** argv){
Base b(0);
void *(Base::*fp)() = &Base::myFunc;
pthread_t t;
pthread_create( &t, NULL, b.*fp, NULL);
pthread_detach( t );
b.myFunc();
sleep(2);
std::cout << b.x << std::endl;
}
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <thread>
class Base{
public:
int x;
Base(int x_): x(x_){}
virtual ~Base(){}
int f()
{
int (Base::*fp)() = &Base::myFunc;
int x = (this->*fp)();
return x;
}
int myFunc()
{
return 1;
}
};
int main(int argc, char** argv){
Base b( 1 );
std::cout << b.f() << std::endl;
int (Base::*fp)() = &Base::myFunc;
std::cout << (b.*fp)() << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment