pthread_create - 非静态成员函数的无效使用
pthread_create - invalid use of non-static member function
我一直在尝试学习如何使用线程,但在创建线程时遇到了困难。我正在这样的 class 构造函数中创建线程...
Beacon::Beacon() {
pthread_create(&send_thread,NULL, send, NULL);
}
发送函数尚未执行任何操作,但它看起来是这样的。
void Beacon::send(void *arg){
//Do stuff
}
每次我 运行 代码都会收到非静态成员函数的无效使用错误。我试过使用 &send,但没有用。我也将最后一个 NULL 参数设置为此,但这没有用。我一直在查看其他示例代码来尝试模仿它,但似乎没有任何效果。我做错了什么?
如果你不能使用 std::thread
我建议你创建一个 static
成员函数来包装你的实际函数,并将 this
作为参数传递给函数。
类似
class Beacon
{
...
static void* send_wrapper(void* object)
{
reinterpret_cast<Beacon*>(object)->send();
return 0;
}
};
然后像这样创建线程
pthread_create(&send_thread, NULL, &Beacon::send_wrapper, this);
我一直在尝试学习如何使用线程,但在创建线程时遇到了困难。我正在这样的 class 构造函数中创建线程...
Beacon::Beacon() {
pthread_create(&send_thread,NULL, send, NULL);
}
发送函数尚未执行任何操作,但它看起来是这样的。
void Beacon::send(void *arg){
//Do stuff
}
每次我 运行 代码都会收到非静态成员函数的无效使用错误。我试过使用 &send,但没有用。我也将最后一个 NULL 参数设置为此,但这没有用。我一直在查看其他示例代码来尝试模仿它,但似乎没有任何效果。我做错了什么?
如果你不能使用 std::thread
我建议你创建一个 static
成员函数来包装你的实际函数,并将 this
作为参数传递给函数。
类似
class Beacon
{
...
static void* send_wrapper(void* object)
{
reinterpret_cast<Beacon*>(object)->send();
return 0;
}
};
然后像这样创建线程
pthread_create(&send_thread, NULL, &Beacon::send_wrapper, this);