我知道传递给 pthread_create API 的线程例程的原型(prototype)为
void *threadproc(void *).
我只是想知道是否可以将 C++ 函数对象用作线程例程。
这是我的代码:
Execution::run 方法接受一个 time_t 变量和一个 functor 作为参数。它会生成一个 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;
};
问题:
我可以将函数对象用作线程函数吗?怎么办?
如何将参数传递给函数对象的 operator() 方法?
在此代码中,父进程终止,而子线程仍在运行。因为我们不想阻塞 run() 方法的调用者。这是一个好习惯吗?孤立线程会在这里引起问题吗?
谢谢。
最佳答案
一个 pthread 函数必须有 C 链接,所以它不能是一个成员函数。严格来说,它甚至不能是静态成员函数,尽管它几乎一直有效。
所以应该做的是创建一个非成员函数,它接受一个 void*
参数,该参数将是指向要作为线程函数的 C++ 对象的指针。该函数可以将 void*
参数转换为调用成员函数的类指针。
参见 In C++, is it safe/portable to use static member function pointer for C API callbacks?
关于c++ - 将 C++ 函数对象作为线程例程传递给 pthread_create 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26419222/