【发布时间】:2019-10-16 00:12:42
【问题描述】:
在类中我声明了线程函数。我使用了 static 关键字,因为没有 static 关键字它不适用于类。
但是如果函数的类型是静态的,我就无法访问类的成员函数和公共变量
#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;
}
任何人告诉我如何在没有静态关键字的情况下使用线程函数。所以我可以访问所有的类变量。
【问题讨论】:
-
您必须直接使用 pthreads 还是允许使用任何 C++11 类,例如 std::thread?
-
是的,如果你想使用类成员,这个方法不能是静态的,尝试使用 pointer to method 从这个:stackoverflow.com/questions/1485983/…
-
您是否查看过任何documentation of
pthread_create以了解其参数是什么以及是否可以使用它们?
标签: c++ linux multithreading pthreads