【发布时间】:2011-06-19 21:51:12
【问题描述】:
我正在尝试设计一个活动对象,一旦创建,基本上就在自己的线程中运行。到目前为止,我所做的是创建一个包含 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;
}
【问题讨论】:
-
请出示代码,否则很难提供任何帮助
-
好的,刚刚尝试将其添加为类函数,由于类型不匹配而无法编译。它正在寻找 void ()(void*) 并得到 void (MyClass::)(void).
标签: c++ multithreading oop class pthreads