Ross Hays
Ross Hays

Reputation: 341

Pthread instance variable running methods from class

I am trying to design an active object of sorts that once created, essentially runs in its own thread. What I have done so far is create a class that contains a pthread instance variable, and then in the constructor for that class, it should send the pthread on its way.

Since pthread_create() takes a function parameters, I am passing it a run() function I setup in my class implementation file.

As of now, my run() function is not a part of the class, it is just sitting in the implementation file, but when I tried to compile it, I get an error saying:

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

Now I understand why the function run() is out of scope, but would it be correct to just add run() to my active object class as a private function, or would that cause other problems if more than one of these objects existed? Heck, would it cause problems with just one of them instantiated?

Ok here is the code, I just didn't think it mattered much. Here is 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();
}

And here is the implementation, 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;
}

Upvotes: 2

Views: 1278

Answers (1)

Troubadour
Troubadour

Reputation: 13421

Your compilation problem is likely that run is defined in your implementation file after you reference it in your constructor. Either move the definition of run before the constructor or insert a declaration of run before the constructor.

As for your problem making it a class member that won't work as pthread_create is looking for a non-member function. You could make it a static method on the class though but read In C++, is it safe/portable to use static member function pointer for C API callbacks? before deciding whether it safe for you to do so (not that you need to now that you know how to use your original function).

Upvotes: 2

Related Questions