C++ Thread function pass by reference

I wonder how we can add a function passing by reference to thread.. Integer examples are so easy at Internet i've found, but couldn't find any example pass by reference ?

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

Upvotes: 1

Views: 1435

Answers (1)

rustyx
rustyx

Reputation: 85531

Solution 1: use std::ref:

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

Solution 2: use a lambda:

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

Upvotes: 2

Related Questions