简体   繁体   English

将C ++函数对象传递给pthread_create函数作为线程例程

[英]Passing a C++ function object to pthread_create function as the thread routine

I know the thread routine that is passed to pthread_create API has the prototype of 我知道传递给pthread_create API的线程例程具有原型

void *threadproc(void *).

I was just wondering if it is possible to use a C++ function object as a thread routine. 我只是想知道是否可以使用C ++函数对象作为线程例程。

Here's my code: 这是我的代码:

Execution::run method takes a time_t variable and a functor as parameters. Execution :: run方法将time_t变量和仿 函数作为参数。 It spawns a POSIX thread in which it spins until the scheduled run time is current and runs some job. 它产生一个POSIX线程,在该线程中它旋转直到预定的运行时间是最新的并运行一些工作。

#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? 如何将参数传递给函数对象的operator()方法?

  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. 因为我们不想阻止run()方法的调用者。 Is this a good practice? 这是一个好习惯吗? Will the orphan thread cause problem here? 孤儿线程会在这里引起问题吗?

Thanks. 谢谢。

A pthread function must have C linkage, so it cannot be a member function. pthread函数必须具有C链接,因此它不能是成员函数。 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. 所以应该做的是创建一个非成员函数,它接受一个void*参数,该参数将是一个指向C ++对象的指针作为线程函数。 That function can cast the void* argument to a class pointer, which calls the member function. 该函数可以将void*参数转换为类指针,该类指针调用成员函数。

See In C++, is it safe/portable to use static member function pointer for C API callbacks? 请参阅在C ++中,为C API回调使用静态成员函数指针是安全/可移植的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM