I am playing with std::async(), I have following code:
#include <iostream>
#include <future>
#include <mutex>
#include <queue>
using namespace std;
std::mutex mu;
queue<int> q;
void shared_cout(int id)
{
mu.lock();
q.push(id*id);
mu.unlock();
}
int main()
{
std::future<void> f[100];
int i =0;
while(true)
{
f[i]= std::async(shared_cout, i);
if(i==99) {
int k=0;
while(k<100){
f[k].get();
if(!q.empty()){
cout<<q.front()<<endl;
q.pop();
} // end of inner if
k++;
} // end of inner - while
i=-1;
} // end of if
i++;
} // end of while
return 0;
}
I am creating 100 std::async calls. The problem here is, If I do say, f[1].get, It is stopping other threads from writing their value to the queue. But how do I modify this so that f[X].get() will not block other async calls to get their values(f[X].get should get called independently instead of sequential manner)?
(Note: I don't want the order to be preserved. Instead f[X].get() should finish as soon as f[X] async call is done.)
Aucun commentaire:
Enregistrer un commentaire