I was trying to send data from the main thread to child thread in an asynchronous manner using future and promise. Here is the code.
#include <bits/stdc++.h>
using namespace std;
int sampleFunc(vector<future<int>> &f) {
int a = f[0].get();
cout <<"got a from promise 1" << endl;
int b = f[1].get();
cout <<"got b from promise 2" << endl;
return a + b;
}
int main() {
int outputVal;
int k = 2;
std::vector<promise<int>> p(k);
vector<future<int>> f(k);
f[0] = p[0].get_future();
f[1] = p[1].get_future();
std::future<int> fu = std::async(std::launch::async,sampleFunc,std::ref(f));
std::this_thread::sleep_for(chrono::milliseconds(1000));
p[0].set_value(2);
std::this_thread::sleep_for(chrono::milliseconds(3000));
p[1].set_value(4);
outputVal = fu.get();
cout << outputVal << endl;
}
The delays might have some other meaning, for example, the values of a and b might not be ready yet( probably we are waiting for some other task to happen inside the main thread).
That, being said, how to pass partial data (asynchronously, like above example) from the child thread to the main thread?. Can this model of data transfer be extended to other threads (child thread to another child thread)?
Thanks !
Aucun commentaire:
Enregistrer un commentaire