lundi 20 avril 2015

C++11 multithreading with class member function

I want to use Multi-Threading in C++11 to call a class member function on its own thread.

I have been able to get a global function to run in Multi-Threading:

#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?

Aucun commentaire:

Enregistrer un commentaire