C++ – Linux C++ threads in classes

Linux C++ threads in classes… here is a solution to the problem.

Linux C++ threads in classes

Hello, I want to complete the class with a method that will be started in a separate thread after creating it. So how did 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);
}

I’m different from the pthread_create in the main and IncWrapper methods, can I change it?

Solution

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;
}
};

Related Problems and Solutions