mercredi 14 septembre 2016

Passing class's member function to std::thread

I have a problem with using std::thread in my code:

Class Timer
{
...
public:
    void Start(bool Asynch = true)
    {
        if (IsAlive())
        {
            return;
        }
        alive = true;
        repeat_count = call_number;
        if (Asynch)
        {
            t_thread = std::thread(&ThreadFunc, this);
        }
        else
        {
            this->ThreadFunc();
        }
    }
    void Stop()
    {
        alive = false;
        t_thread.join();
    }
...
}

I get following error:

error C2276: '&': illegal operation on bound member function expression

t_thread is class's private std::thread instance, ThreadFunc() is private member function of the class that returns void;

I think I understand that there are 2 ways to send member function to std::thread, if the function is static I would use t_thread = std::thread(threadfunc); But I don't want ThreadFunc to be static, and doing it like this gives me error.

I think I solved the problem by creating another function:

std::thread ThreadReturner()
{
    return std::thread([=] { ThreadFunc(); });
}
...
t_thread = ThreadReturner();

This way I don't get errors, but I don't understand why first one doesn't work.

Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire