syntax for starting a thread in a template class

116 views Asked by At

I create an object of type T in a template class.

template <class T>
class worker
{
public:
    worker() { obj = new T(app_cfg);}
    ~worker() { if (obj) { delete obj; obj = nullptr; }}

    void start();

private:
    T * obj = nullptr;
    std::atomic<bool> is_work_{ false };
    std::thread thread_{};

};

The object has a check() method. I want to run a check() method on a thread. And I do it like this:

template <class T>
void worker<T>::start() {
    is_work_ = true;
    thread_ = std::thread(&T::check, obj, is_work_);
}

After that an error occurs:
Error C2661 no overloaded function taking 3 arguments

I think that the problem is in the thread launch syntax.
How to correctly specify the parameters for launch?

1

There are 1 answers

2
Pepijn Kramer On

Possible solution :

#include <future>       // https://en.cppreference.com/w/cpp/thread/future
#include <iostream>

template <class T>
class worker_t
{
public:
    void start()
    {
        // I prefer using std::async over std::thread
        // it has better abstraction and automatic synchonization on future destructor
        // future also allows you to return values and errors (exceptions) from the 
        // background thread to the calling thread.
        // The [&]{...} is a lambda function, easy to call 
        // member functions this way (without the need for
        // complicated member function pointers)
        m_future = std::async(std::launch::async, [&] { obj.check(); });
    }

private:
    T obj; // no need for a pointer just create a member
    std::future<void> m_future;
};

class object_t
{
public:
    void check()
    {
        std::cout << "Hello World!";
    }
};

int main()
{

    worker_t<object_t> worker;
    worker.start();

    // destructor of worker_t will synchronize with its member future
    // ensuring the thread also did its work. 
    // before exiting the program

    return 0;
}