在类中我声明了线程函数。我使用了 static 关键字,因为没有 static 关键字它不能与类一起使用。
但是如果函数的类型是静态的,我就无法访问类的成员函数和公共(public)变量
#include <iostream>
#include <pthread.h>
using namespace std;
class Base{
private:
static void * fpga_read(void*); // Thread function
void foo_2();
public:
/* member variables */
void foo(void);
protected:
int b;
};
void Base::foo(void)
{
pthread_t id;
pthread_create(&id, NULL,fpga_read,NULL);
cout << "\nInside base class" << endl;
}
void * Base::fpga_read(void *p)
{
cout << "\nInside thread function " << endl;
// error: invalid use of member ‘Base::b’ in static member function
cout << "Value of B inside thread class" << b;
int b;
}
int main()
{
Base a;
a.foo();
pthread_exit(NULL);
return 0;
}
任何人都可以告诉我如何在不使用 static 关键字的情况下使用线程函数。这样我就可以访问所有类变量。
最佳答案
您不需要任何静态成员函数。您可以使用 pthread_create
的 argument 参数,无状态 lambda 函数衰减为普通函数指针,使代码几乎看起来像您实际编写的代码:
Godbolt 链接:https://godbolt.org/z/QIGNUX
#include <iostream>
#include <pthread.h>
class Base {
public:
Base(int state) noexcept : b{state} {}
void foo();
private:
int b;
void fpga_read() {
std::cout << "Value of B inside thread class" << b;
}
};
void Base::foo()
{
pthread_t thread;
pthread_create(&thread, nullptr, [](void* that) -> void* {
Base* this_ = static_cast<Base*>(that);
this_->fpga_read();
return nullptr;
}, static_cast<void*>(this));
pthread_join(thread, nullptr);
}
关于c++ - 没有类静态声明的 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56376540/