2011-06-19 112 views
2
运行方法

我想设计一个曾经创建的排序的主动对象,本质上运行在它自己的线程。到目前为止,我所做的是创建一个包含pthread实例变量的类,然后在该类的构造函数中,它应该发送pthread。Pthread实例变量从类

由于pthread_create()接受一个函数参数,我将它传递给我的类实现文件中的run()函数。

截至目前,我的run()函数不是类的一部分,它只是坐在实现文件,但是当我试图编译它,我得到一个错误说:

"error: ‘run’ was not declared in this scope" 

现在我明白了为什么函数run()超出范围,但将run()作为私有函数添加到我的活动对象类是否正确,或者如果存在多个这样的对象会导致其他问题?哎呀,它会导致只有其中一个实例化的问题?

好的,这里是代码,我只是不认为它很重要。这里是MyClass.hpp

class MyClass { 

private: 
pthread_t thread; 

    ObjectManager *queue; 
int error; 

    // just added this, but the compiler still doesn't like it 
    void *run(void *arg); 

public: 

    MyClass(); 
    ~MyClass(); 

void start(); 
} 

这里是实施,MyClass.cpp:

#include "MyClass.hpp" 

void MyClass::start() { 
if (queue == NULL) 
    return; 

int status = pthread_create(&thread, NULL, run, (void *) queue); 
if (status != 0) { 
    error = status; 
    return; 
} 

} 


void *MyClass::run(void *arg) { 
bool finished = false; 
while (!finished) { 
     // blah blah blah 
} 
return NULL; 
} 
+0

请显示代码,否则将很难提供任何帮助 – nos

+0

好吧,只是尝试将它添加为类函数,并且由于类型不匹配而无法编译。它正在寻找void *(*)(void *)并且获取void *(MyClass ::)(void *)。 –

+0

[pthread Function from a Class]的可能重复(http://stackoverflow.com/questions/1151582/pthread-function-from-a-class) –

回答

2

你编译的问题很可能是run在您的实现文件中定义你引用它在你的构造函数。在构造函数之前移动run的定义,或者在构造函数之前插入run的声明。

至于你的问题,使其成为一个类的成员,将不起作用pthread_create正在寻找一个非成员函数。你可以在课上做一个静态的方法,但是在你决定是否安全之前(不是你现在需要知道如何使用你的原始函数),而是读In C++, is it safe/portable to use static member function pointer for C API callbacks?

+0

够简单,谢谢。不知道为什么我错过了,但谢谢。 –

+1

这已被询问和回答很多次。始终 - 始终是静态成员函数出现,但仍然**总是错误**。 –

+0

阅读:http://stackoverflow.com/q/6352280/14065 –