gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:58:21 24 4
gpt4 key购买 nike

我正在尝试设计一个事件对象,一旦创建,基本上就在自己的线程中运行。到目前为止,我所做的是创建一个包含 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com