Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/137.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;线程函数按引用传递_C++_Multithreading - Fatal编程技术网

C++ C++;线程函数按引用传递

C++ C++;线程函数按引用传递,c++,multithreading,C++,Multithreading,我想知道如何添加一个通过引用传递给线程的函数。。整数示例在Internet上很容易找到,但找不到任何通过引用传递的示例 #include <iostream> #include <thread> void add(int a, int b) { std::cout << a + b << std::endl; } void sub(int c, int d) {

我想知道如何添加一个通过引用传递给线程的函数。。整数示例在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;
    }
#包括
#包括
无效添加(内部a、内部b)
{

标准::cout解决方案1:使用:

解决方案2:使用lambda:

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

在变量上使用std::ref和std::cref。另外,请查看std::bind。它使用相同的技术。非常感谢。它很有效。
    int number1 = 25;
    int number2 = 50;
    std::thread third([&] { addp(number1, number2); });