Skip to content

Instantly share code, notes, and snippets.

@Infinitusvoid
Last active January 15, 2023 14:02
Show Gist options
  • Save Infinitusvoid/41546aec0487b145d32af7316e75cb6f to your computer and use it in GitHub Desktop.
Save Infinitusvoid/41546aec0487b145d32af7316e75cb6f to your computer and use it in GitHub Desktop.
C++ : How to use std::async and std::future to push to vector from multiple threads ( multithreading, threads )?
#include <iostream>
#include <future>
static std::mutex s_ElementMutex;
std::vector<std::future<void>> futures;
struct Element
{
int i;
double b;
void display()
{
std::cout << " Index of element : " << i << " computed value : " << b << "\n";
}
};
// we need a pointer not a reference
static void f_compute(std::vector<Element>* data, std::string file_path, int index)
{
double result = (double)index * (double)index;
// some task just to show that what first start computing does not always end first.
for (int i = 0; i < 10000000; i++)
{
result += 1;
}
for (int i = 0; i < 10000000; i++)
{
result -= 1;
}
//We have to lock the thing we are modifily from multiple threads
//you have to lock the resource
//do it to what you want to do todo ( such is modifily it )
//and than unlock it so that the other thread can access it
//What this actually means is his lock will lock it's mutex at place
//so that it can't be locked by any other thread
//until is been unlocked
//when we exit this function it becomes unlocked ( Resource acquisition is initialization ) RAII
std::lock_guard<std::mutex> lock(s_ElementMutex);
data->push_back(Element{ index, result });
}
std::vector<Element> elements;
int main()
{
//and the way you do something like this is by using something like a mutex
//we have to lock tis element vector while is being modified
//we lock it
//we push our element
//we unlock it
//that lock if another element is being push_back concurently
//if tries to push back at the same time before we finish pushing back in current thread
//it will just wait until we are done and unlock that meshes vector
//and when we unclock that meshes vector than it can push back it's mesh
std::string path = "";
//start
for (int i = 0; i < 10; i++)
{
futures.push_back(std::async(std::launch::async, f_compute, &elements, path, i));
}
//wait
for (int i = 0; i < futures.size(); i++)
{
futures[i].wait();
}
//display
for (int i = 0; i < elements.size(); i++)
{
elements[i].display(); // the order can be changed.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment