Starting a member function in a thread using class constructor

442 views Asked by At

I have a class containing a member function which I want to pass to std::thread's constructor.

#include <thread>
#include <iostream>

struct StatsClientImpl
{
    std::thread t;
    size_t q_len;

    StatsClientImpl() : q_len(0)
    {
        t = std::thread(&StatsClientImpl::de_q, this);
    }

    ~StatsClientImpl()
    {
        if (t.joinable())
            t.join();
    }

    void de_q()
    {
        std::cout << "in de_q\n";
    }
};

int main()
{
    StatsClientImpl s;
}

I get the following errors:

/Users/apple/platform/stats-client/src/main/cpp/StatsClientImpl.cpp:21:17: error: no matching constructor for initialization of 'std::thread'
    std::thread te(&StatsClientImpl::de_q, this);
                ^  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:374:9: note: candidate constructor template not viable: requires single argument '__f', but 2 arguments were provided
thread::thread(_Fp __f)
        ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:263:5: note: candidate constructor not viable: requires 1 argument, but 2 were provided
    thread(const thread&);
    ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:270:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
    thread() _NOEXCEPT : __t_(0) {}
1

There are 1 answers

6
Serge Rogatch On BEST ANSWER

C++11 thread allows to call a non-static method directly. The syntax you used is intended for that, just replace de_q_caller with de_q:

t = std::thread(&StatsClientImpl::de_q, this);

UPDATE: because your compiler does not seem to allow that, try

t = std::thread(std::bind(&StatsClientImpl::de_q, this));

clang compiler may require to add the following compiler option:

-std=c++11