Pthread 和函数指针
Pthread and function pointers
我对 pthread 的工作原理有点困惑 - 具体来说,我很确定 pthread 接受一个指向函数的指针,该函数将 void 指针作为参数(如果我错了请纠正我),并且我有以这种方式声明了我的函数,但我仍然遇到错误。这是我正在苦苦挣扎的代码:
void eva::OSDAccessibility::_resumeWrapper(void* x)
{
logdbg("Starting Connection.");
_listener->resume();
logdbg("Connected.");
pthread_exit(NULL);
}
void eva::OSDAccessibility::resumeConnection()
{
long t;
_listener->setDelegate(_TD);
pthread_t threads[1];
pthread_create(&threads[0], NULL, &eva::OSDAccessibility::_resumeWrapper, (void *)t);
}
我得到的错误是:
No matching function for call to pthread_create.
您不一定非得告诉我如何修复代码(当然我会很感激),我更感兴趣的是为什么会出现此错误以及我对 pthread 的理解是否正确。谢谢! :)
你的函数签名必须是void * function (void*)
如果从 C++ 代码调用,方法必须是静态的:
class myClass
{
public:
static void * function(void *);
}
使用非静态方法的解决方案如下:
class myClass
{
// the interesting function that is not an acceptable parameter of pthread_create
void * function();
public:
// the thread entry point
static void * functionEntryPoint(void *p)
{
((myClass*)p)->function();
}
}
并启动线程:
myClass *p = ...;
pthread_create(&tid, NULL, myClass::functionEntryPoint, p);
我对 pthread 的工作原理有点困惑 - 具体来说,我很确定 pthread 接受一个指向函数的指针,该函数将 void 指针作为参数(如果我错了请纠正我),并且我有以这种方式声明了我的函数,但我仍然遇到错误。这是我正在苦苦挣扎的代码:
void eva::OSDAccessibility::_resumeWrapper(void* x)
{
logdbg("Starting Connection.");
_listener->resume();
logdbg("Connected.");
pthread_exit(NULL);
}
void eva::OSDAccessibility::resumeConnection()
{
long t;
_listener->setDelegate(_TD);
pthread_t threads[1];
pthread_create(&threads[0], NULL, &eva::OSDAccessibility::_resumeWrapper, (void *)t);
}
我得到的错误是:
No matching function for call to pthread_create.
您不一定非得告诉我如何修复代码(当然我会很感激),我更感兴趣的是为什么会出现此错误以及我对 pthread 的理解是否正确。谢谢! :)
你的函数签名必须是
void * function (void*)
如果从 C++ 代码调用,方法必须是静态的:
class myClass { public: static void * function(void *); }
使用非静态方法的解决方案如下:
class myClass
{
// the interesting function that is not an acceptable parameter of pthread_create
void * function();
public:
// the thread entry point
static void * functionEntryPoint(void *p)
{
((myClass*)p)->function();
}
}
并启动线程:
myClass *p = ...;
pthread_create(&tid, NULL, myClass::functionEntryPoint, p);