CPP
cpp
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
26
27
28
// Created by Ketan Lalcheta
/*
There is an algorithm that is divided into 5 parts.
They must be executed one by one in different threads, using the result of the previous step.
How do you implement it?
*/
#include <iostream>
#include <future>
using namespace std;
int getNext(char threadName, int valPrev) {
int val = rand() %10 + 1;
cout << "Thread " << threadName
<< " with value: " << val << '\n';
return val + valPrev;
}
int main() {
srand(time(0));
int n = 0;
for(char c='A'; c<='E'; c++)
n = async(getNext, c, n).get();
cout << "final n = " << n << endl;
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run