【问题标题】:C++ Thread function pass by referenceC++线程函数通过引用传递
【发布时间】:2018-05-19 11:11:59
【问题描述】:

我想知道如何添加一个通过引用传递给线程的函数。整数示例在 Internet 上很容易找到,但找不到任何通过引用传递的示例?

    #include <iostream>
    #include <thread>

    void add(int a, int b)
    {

        std::cout <<  a + b << std::endl;

    }

    void sub(int c, int d) {
        std::cout<< c - d << std::endl;
    }

    void addp(int &a1, int &a2) {
        std::cout << a1 + a2 << std::endl;
    }

    int main() {
        int number1 = 25;
        int number2 = 50;
        toplamap(number1, number2);
        std::thread first(add, 10, 29);
        std::thread second(sub, 29, 10);
        std::thread third(addp, number1, number2);
        first.join();
        second.join();
        third.join();

        return 0;
    }

【问题讨论】:

  • 对变量使用 std::ref 和 std::cref。另外,请查看 std::bind。它使用相同的技术。
  • 非常感谢.. 成功了。

标签: c++ multithreading


【解决方案1】:

解决方案1:使用std::ref

    int number1 = 25;
    int number2 = 50;
    std::thread third(addp, std::ref(number1), std::ref(number2));

解决方案 2:使用 lambda:

    int number1 = 25;
    int number2 = 50;
    std::thread third([&] { addp(number1, number2); });

【讨论】:

    猜你喜欢
    • 2020-05-03
    • 1970-01-01
    • 2013-06-17
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    相关资源
    最近更新 更多