c++ - Pthread实例变量运行类中的方法

标签 c++ multithreading oop class pthreads

我正在尝试设计一个事件对象,一旦创建,基本上就在自己的线程中运行。到目前为止,我所做的是创建一个包含 pthread 实例变量的类,然后在该类的构造函数中,它应该发送 pthread。

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

截至目前,我的 run() 函数不是类的一部分,它只是位于实现文件中,但是当我尝试编译它时,我收到一条错误消息:

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

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

好的,这是代码,我只是觉得这无关紧要。这是 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;
}

最佳答案

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

至于你的问题,让它成为一个不能工作的类成员,因为 pthread_create 正在寻找一个非成员函数。你可以使它成为类的静态方法,但请阅读 In C++, is it safe/portable to use static member function pointer for C API callbacks?在决定这样做对您来说是否安全之前(不需要,因为您现在知道如何使用您的原始功能)。

关于c++ - Pthread实例变量运行类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6405315/

相关文章:

java - 如何在Java中的两个线程之间创建竞争情况?

database - ORM是什么意思?

c++ - 关于静态变量的问题

php - 我该如何改进这段代码

c++ - 在排序的 STL 容器中查找给定键的 "best matching key"

c++ - 数值食谱中显然 undefined variable

c++ - 为什么 STL 的 next_permutation 实现不使用二分查找?

python - 在 pythran 中使用日期时间

c - 通过条件变量唤醒的线程何时运行?

c# - .net 中 Thread 类和 ProcessThread 类的区别?