我需要在类中调用另一个方法来调用另一个新线程中的同一个类,但是遇到了一些麻烦。我得到了编译错误:“'这个'不可用于静态成员函数”。我举了一个例子,因为我不能在这里发布原始代码。如何使一个方法在新线程的同一个类中调用另一个方法?
基本上,我发生了什么事是我的班级的一个对象(在下面的例子中被称为aClass
),然后我调用一个方法,如do_stuff()
。 do_stuff()
方法使用pthread_create
在新线程中调用print_number()
方法。问题是,当我去编译时,我得到一个错误,说我不能使用this
,因为我的print_number()
方法是静态的。如果我没有将print_number()
方法设为静态,则pthread_create
会抱怨它不是兼容的类型。
我明白为什么我不能在print_number()
方法本身内部使用this
,因为它是静态的,可以在没有对象的情况下被调用。但是,在我的print_number()
方法中,我没有使用this
。我正在使用指向我创建的对象的指针。在do_stuff()
我使用this
将我创建的对象的引用传递给print_number
,但我在print_number
本身中不使用this
。所以我不明白这个问题是什么。谢谢您的帮助!
class aClass
{
private:
number;
public:
void do_stuff(void);
static void* print_number(void* arg)
}
// this method is called first
void aClass::do_stuff()
{
number = 4;
pthread_t thread1;
pthread_create(&thread1, NULL, print_number, this);
.....
}
//this method is called from the do_stuff() method in a new thread
void* aClass::print_number(void* arg)
{
aClass* objPTR = (aClass*)arg;
printf("number = %d", objPTR->number);
}
//don't get caught up here.. the point is that an object is created and
// the "do_stuff()" method is called
int main()
{
//all the usual stuff here
aClass someObject;
someObject.do_stuff();
}
查找“pthread_create类方法”。例如,这个问题可以解决这个问题:(http://stackoverflow.com/questions/7809987/c-how-to-define-a-class-method-as-a-start-routine-to -thread-with-pthread-lib) – MichaelGoren