Multithreading

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 .

Last edited on
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?
I couldnt find any tutoriouls about
A value which provided from one of the threads , and use that value in the main thread . ( like my example )

I mean ı need you to show me an example about it
Last edited on
C++11 makes it pretty straightforward:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <thread>
#include <future>
#include <iostream>

int main()
{
    std::cout << "Enter two numbers\n";
    int a, b;
    if(std::cin >> a >> b)
    {
        auto r1 = std::async(std::launch::async, [&]{return a*a;});
        auto r2 = std::async(std::launch::async, [&]{return b*b;});
        std::cout << "The result: " << r1.get() + r2.get() << '\n';
    }
}
There are caveats though:

1
2
3
4
5
6
        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' 
I need the programme to be in this form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include<thread>
using namespace 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;
}
You might do something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
#include<thread>
#include <functional>

using namespace 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.

thanks it helped alot
Topic archived. No new replies allowed.