You can not cast std::function
to function pointer. But you can use std::thread
, which will work with any callbable, including std::function
.
If, for whatever reason, you can't use std::thread
, you can create a local class and a static member function there, to call the std::function
.
Something along following lines:
#include <functional>
#include <pthread.h>
void parallel(std::function<void(int)>&& lambda){
struct caller {
static void* callme_static(void* me) {
return static_cast<caller*>(me)->callme();
}
void* callme() {
callable(arg);
return nullptr;
}
caller(std::function<void(int)> c, int a) : callable(c),
arg(a) {}
std::function<void(int)> callable;
const int arg;
};
pthread_t threadid;
int arg = 0;
caller c(lambda, arg);
//Want to call lambda(1) from the created thread
pthread_create(&threadid, NULL, &caller::callme_static, &c);
}
This could be generalized into universal caller, but that would be exactly what std::thread
already does, so if universal caller is desired, one could simply copy-paste std::thread
.