You cannot pass multiple arguments to pthread_create
, but you can pack multiple arguments into a struct
that you create specifically for the purpose of packing the arguments. Make the struct
"private" to your implementation by defining it in the cpp file, rather than in the header. Pass a pointer of that struct to pthread_create
, then "unpack" it in the helper to call the member function.
Let's assume that the thread implementation is a member function threadRun
defined as follows:
int MyClass::threadRun(int arg1, string arg2) {
... // Do useful work
return 42; // Return an important number
}
To call this function, define a thread_args
struct
like this:
struct thread_args {
MyClass *instance;
int arg1;
string arg2;
};
Now your helper function can be defined as 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 an `int` pointer to pass back thread runner's results
}
The function that starts up the thread could look like 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, &args);