Created
February 21, 2018 16:00
-
-
Save melvyniandrag/7dfeb45e8cc6ee09a0191b928ecf5e7e to your computer and use it in GitHub Desktop.
pass multiple args to a pthread
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 <pthread.h> | |
#include <iostream> | |
class A | |
{ | |
public: | |
A( int _i, int *_p ) : i( _i ), p( _p ){} | |
int i; | |
int *p; | |
void squareMyPtr() | |
{ | |
*p = (*p)*(*p); | |
} | |
}; | |
class B : public A | |
{ | |
public: | |
B( int _i, int* _p, int _j ): A( _i, _p ), j(_j){} | |
int j; | |
}; | |
struct threadArgs | |
{ | |
threadArgs( A* a, B* b): a_ptr(a), b_ptr(b){} | |
A* a_ptr; | |
B* b_ptr; | |
}; | |
void *threadMain( void* ta ) | |
{ | |
threadArgs* args = static_cast<threadArgs*>( ta ); | |
std::cout << "args addr: " << args << std::endl; | |
A* a = static_cast<A*>(args->a_ptr); | |
B* b = static_cast<B*>(args->b_ptr); | |
a->squareMyPtr(); | |
b->squareMyPtr(); | |
return NULL; | |
} | |
int main() | |
{ | |
int i = 10; | |
A a(i, &i); | |
a.squareMyPtr(); | |
std::cout << a.i << std::endl; | |
std::cout << i << std::endl; | |
std::cout << *(a.p) << std::endl; | |
int d = 100; | |
B b(i, &i, d); | |
threadArgs ta( &a, &b); | |
std::cout << "ta addr: "<< &ta << std::endl; | |
pthread_t thread1; | |
pthread_create(&thread1, NULL, *threadMain, (void*) &ta); | |
pthread_join(thread1, NULL); | |
std::cout << i << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment