I need an easy example about multithreading .
I want to input 2 numbers and ı want;
first thread to find first numbers square,
second thread to find second numbers cube,
and in tne main thread it adds those two numbers other threads found .
Multithreading is a pretty big topic. It commonly hangs up even experienced programmers. Where are you stuck at? Can you show us some code that you've tried?
auto r1 = std::async(std::launch::async, [&]{return a*a;});
// 'a' MUST NOT be modified after this line
auto r2 = std::async(std::launch::async, [&]{return b*b;});
// 'b' MUST NOT be modified after this line
std::cout << "The result: " << r1.get() + r2.get() << '\n';
// now safe to modify 'a' and/or 'b'
#include<iostream>
#include<thread>
usingnamespace std;
int kare(int a){
return a*a;
}
int kup(int b){
return b*b*b;
}
int main(){
int a,b,z;
thread portal1(kare,2);
thread portal2(kup,3);
a=portal1.join();//ı know this 2 line is wrong
b=portal2.join;//but ı need an alternative .
cout<<a+b;
cin>>z;
}
#include<iostream>
#include<thread>
#include <functional>
usingnamespace std;
void kare(int a, int& r){
r = a*a;
}
void kup(int b, int& r){
r = b*b*b;
}
int main(){
int a, b;
thread portal1(kare, 2, std::ref(a));
thread portal2(kup, 3, std::ref(b));
portal1.join();
portal2.join();
cout << a + b;
}
if you're stuck using std::thread. The solution using std::async is a better one, although capturing by value rather than reference should probably be preferred.