c++ - Pthread member function with arguments -
i'm trying use pthreads classes. i've read best solution use threads member functions define static helper function , call thread function inside. requires 'this' pointer passed argument pthread_create. how implement if original thread function has argument? there way pass multiple arguments pthread_create?
you cannot pass multiple arguments pthread_create
, can pack multiple arguments struct
create purpose of packing arguments. make struct
"private" implementation defining in cpp file, rather in header. pass pointer of struct pthread_create
, "unpack" in helper call member function.
let's assume thread implementation member function threadrun
defined follows:
int myclass::threadrun(int arg1, string arg2) { ... // useful work return 42; // return important number }
to call function, define thread_args
struct
this:
struct thread_args { myclass *instance; int arg1; string arg2; };
now helper function can defined follows:
void* thread_helper(void *voidargs) { thread_args *args = (thread_args*)voidargs; int res = args->instance->threadrun(args->arg1, args->arg2); return new int(res); // return `int` pointer pass thread runner's results }
the function starts thread this:
... myclass runner; thread_args args; args.instance = &runner; args.arg1 = 123; args.arg2 = "hello"; pthread_t thread_id; int s = pthread_create(&thread_id, null, &thread_helper, &targs);
Comments
Post a Comment