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.
std::bindit makes threading object member invokes trivial. I could sing its praises from the mountain tops for hours, and cannot advise strongly enough that you investigate whether it is available for your target platforms. If it is, use it.void*and use an according function for the function part. The rest should follow or be easy to figure out, but you should read what WhozCraig, because it's good advise and a much better approach.