[英]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.