Linux C ++ thread in class

Hi, I want to make a class using a method that starts in a separate thread after creating the class. Here is how I do it:

class Devemu {
int VarInc;

void Increm() {
    for(;;) {
        if (VarInc > 532) VarInc = 0;
        else VarInc++;
    }
}

public:
static void* IncWrapper(void* thisPtr) {
    ((Devemu*) thisPtr)->Increm();
    return NULL;
}
Devemu() {
    VarInc = 0;
}
int Var() {
    return VarInc;
}
};
int main(int argc, char** argv) {

Devemu* em = new Devemu();
pthread_t thread_id;
pthread_create(&thread_id, NULL, &Devemu::IncWrapper, NULL);


for(int i = 0 ;i < 50; i++) {
printf("%d\n", em->Var());
}
return (EXIT_SUCCESS);
}

Unlike pthread_create in the main and IncWrapper method, can I change this?

+3
source share
2 answers

Yes, you can put it in the constructor if you want:

class Devemu {
int VarInc;
pthread_t thread_id;

void Increm() {
    for(;;) {
        if (VarInc > 532) VarInc = 0;
        else VarInc++;
    }
}

public:
static void* IncWrapper(void* thisPtr) {
    ((Devemu*) thisPtr)->Increm();
    return NULL;
}
Devemu() {
    VarInc = 0;

    pthread_create(&thread_id, NULL, &Devemu::IncWrapper, NULL);
}
int Var() {
    return VarInc;
}
};
+4
source

I believe that it is better to create a thread creation in a separate member function as follows:

class Devemu {

    ...

    void run()
    {
        pthread_create(&thread_id, NULL, &Devemu::IncWrapper, NULL);
    }

    ...
};

Not really in ctor, because sometimes you (or anyone who uses your code) can forget this thread created in ctor and start coding, for example:

Devemu m;
...
Devemu m1;
...

creates unnecessary threads, like instances of a class.

0
source

All Articles