Passing a C++ function object to pthread_create fu

2020-03-26 06:36发布

问题:

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:

  1. Can I use a function object as thread function? How?

  2. How do I pass parameters to the operator() method of the function object?

  3. 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.

回答1:

A pthread function must have C linkage, so it cannot be a member function. Strictly speaking, it cannot even be a static member function, even though that will work almost all the time.

So what should be done is to create a non-member function that takes a void* argument that will be a pointer to the C++ object to be the thread function. That function can cast the void* argument to a class pointer, which calls the member function.

See In C++, is it safe/portable to use static member function pointer for C API callbacks?