繁体   English   中英

C ++线程函数通过引用传递

[英]C++ Thread function pass by reference

我不知道我们如何添加一个通过引用传递给线程的函数。我在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;
    }

解决方案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); });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM