I know the thread routine that is passed to pthread_create API has the prototype of
void *threadproc(void *).
I was just wondering if it is possible to use a C++ function object as a thread routine.
Here's my code:
Execution::run method takes a time_t variable and a functor as parameters. It spawns a POSIX thread in which it spins until the scheduled run time is current and runs some job.
#include <pthread.h>
#include <ctime>
#include <unistd.h>
#include <iostream>
using namespace std;
class ThreadFunctor
{
public:
void *operator()(time_t runTime)
{
time_t curTime;
double timeDiff;
time(&curTime);
timeDiff = difftime(runTime, curTime);
if (timeDiff > 0)
{
sleep(timeDiff);
}
//
// doSomething();
//
return NULL;
}
};
class Execution
{
public:
Execution() {}
int run(time_t scheduledTime, ThreadFunctor &threadProc)
{
int rc = pthread_create(&mThread, NULL, threadProc, &scheduledTime);
if (rc != 0)
{
cerr << "Thread creation failed\n";
return -1;
}
return 0;
}
private:
pthread_t mThread;
};
Questions:
Can I use a function object as thread function? How?
How do I pass parameters to the operator() method of the function object?
In this code, the parent process terminates while the child thread is still running. Because we don't want to block the caller of run() method. Is this a good practice? Will the orphan thread cause problem here?
Thanks.