Created
November 1, 2017 17:08
-
-
Save melvyniandrag/b9ac21a54fa938ca2e6e94953fc9aca2 to your computer and use it in GitHub Desktop.
function ptrs to member functions and pthreads with member functions.
This file contains hidden or 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 <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; | |
} |
This file contains hidden or 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 <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