Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 multithreading with class member function [duplicate]

I want to use multithreading in C++11 to call a class member function in its own thread. I have been able to get this to work with a global function:

#include <thread>
#include <iostream>

void Alpha(int x)
{
    while (true)
    {
        std::cout << x << std::endl;
    }
}

int main()
{
    std::thread alpha_thread(Alpha, 5);
    alpha_thread.join();

    return 0;
}

However, I cannot get it to compile with a class member function:

#include <thread>
#include <iostream>

class Beta
{
public:
    void Gamma(int y)
    {
        while (true)
        {
            std::cout << y << std::endl;
        }
    }
};

int main()
{
    Beta my_beta;
    std::thread gamma_thread(my_beta.Gamma, 5);
    gamma_thread.join();

    return 0;
}

The compile error is:

no matching function for call to 'std::thread::thread(<unresolved overloaded function type>)'
 std::thread gamma_thread(my_beta.Gamma, 5);
                                    ^

What am I doing wrong?

like image 217
Karnivaurus Avatar asked Apr 20 '15 17:04

Karnivaurus


1 Answers

You need to pass two things: a pointer-to-member, and the object. You cannot call a non-static member function (like Gamma) in C++ without an object. The correct syntax would be:

std::thread gamma_thread(&Beta::Gamma, // the pointer-to-member
                         my_beta,      // the object, could also be a pointer
                         5);           // the argument

You can think of my_beta here as being the first argument to Gamma(), and 5 as the second.

like image 137
Barry Avatar answered Sep 19 '22 17:09

Barry