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;
}
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); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.