c++ - 如何在线程c++11中调用二类成员函数中的一类成员函数

标签 c++ multithreading c++11

我有两个类(class)。

class first
{
    public:
        int sum (int a, int b)
        {
            return a+b;
        }
};

class second
{
    private:
        std::thread t1, t2;
        int sum (int a, int b, int c)
        {
            return a+b+c;
        }
    public:
        void execute()
        {
            t1 = std::thread (&second::sum, this, 10,20,30);                //calling same class function
            t2 = std::thread (&first::sum, /*what will be here*/, 10,20);   // trying to call another class function
        }

};

int main()
{
    second s;
    s.execute();
    return 0;
}

我需要传递什么来代替/* 这里会是什么 */

最佳答案

您需要一个 first 的实例(或指向至少与线程一样长的 first 实例的指针):

传递实例:

first f;
t2 = std::thread (&first::sum, f, 10,20);  

传递一个指针:

// assume m_f is a data member of type first
t2 = std::thread (&first::sum, &m_f, 10,20); 

选择哪一个取决于所需的语义。在这种情况下,first::sum 成为成员非静态成员函数(或根本不是成员函数)毫无意义。

如果您选择使 first::sum 成为 static 成员,那么您将不需要 first 的实例:

t2 = std::thread (&first::sum, 10, 20); 

关于c++ - 如何在线程c++11中调用二类成员函数中的一类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23201706/

相关文章:

c++ - GpuMat::upload 在线程中调用时停止?

java - 销毁/停止线程

c++ - 是否可以在 cpp 中创建一组指向对象的指针?

c++ - std::enable_if 和 std::shared_ptr

c++ - 如何将来自用户定义文字的可变字符模板参数转换回数字类型?

c++ - 使用 libzip 从 .zip 获取文件(文本除外)

c++ - 将指向 C++ 成员函数的指针传递给 C API 库

c++ - 从文本文件读取数据。我需要做两件事,首先我需要读取点数

c# - await 运算符没有像我预期的那样等待

c# - Timer.Change() 会返回 false 吗?