具有类成员函数的C ++ 11多线程

具有类成员函数的C ++ 11多线程

问题描述:

我想在C ++ 11中使用多线程在其自己的线程中调用类成员函数.我已经能够将其与全局函数一起使用:

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;
}

编译错误为:

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

我在做什么错了?

您需要传递两件事:成员指针和对象.没有对象,就不能在C ++中调用非静态成员函数(如Gamma).正确的语法为:

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

您可以将my_beta视为Gamma()的第一个参数,将5视为第二个参数.

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