Say I have the following function:
bool foo (int a); // This method declaration can not be changed.
How do I create a pthread for this? And how
You could encapsulate the function you want to invoke in a function object, and then invoke that function object from within your pthread function:
First, define a function object that encapsulates your function call.
struct foo_functor {
// Construct the object with your parameters
foo_functor(int a) : ret_(), a_(a) {}
// Invoke your function, capturing any return values.
void operator()() {
ret_ = foo(a_);
}
// Access the return value.
bool result() {
return ret_;
}
private:
bool ret_;
int a_;
};
Second, define a function with the appropriate pthread signature that will invoke your function object.
// The wrapper function to call from pthread. This will in turn call
extern "C" {
void* thread_func(void* arg) {
foo_functor* f = reinterpret_cast(arg);
(*f)();
return 0;
}
}
Finally, instantiate your function object, and pass it as a parameter to the thread_func function.
foo_functor func(10);
pthread_t pid;
pthread_create(&pid, NULL, thread_func, &func);
pthread_join(pid, NULL);
bool ret = func.result();