C++ Thread access issue with class member variables

The problem is with the constructor of std::thread, it copies/moves by default.

std::thread AThread(&A::threadCall, *this);

this copies the object into the new thread, so checking the active variable in the new object has no effect.

you can remove the *

std::thread AThread(&A::threadCall, this);

you pass the object pointer into the new thread, it will call like the method like this(*this).threadCall().

Edit: as the comments say, this is not guarantee to be thread safe, you need to use std::atomic<bool> to be safe.


What you need to do is pass an A class pointer as an argument to your function that is your thread.

void A::startThread()
{
    active = true;
    std::thread AThread(threadCall, this);
    AThread.detach();
}
void A::threadCall(A *aClass)
{
    printf("[T] Thread Started\n");
    while (aClass->active)
    {
        std::this_thread::sleep_for(std::chrono::seconds(2));
    }
    printf("[T] Thread Ended\n");
}