C ++线程函数通过引用传递 [英] C++ Thread function pass by reference
本文介绍了C ++线程函数通过引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道我们如何添加一个通过引用传递给线程的函数.我发现Internet上的整数示例是如此简单,但是找不到任何通过引用传递的示例?
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;
}
推荐答案
解决方案1 :使用 解决方案2 :使用lambda:
Solution 2: use a lambda:
int number1 = 25;
int number2 = 50;
std::thread third([&] { addp(number1, number2); });
这篇关于C ++线程函数通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文