Basically what I would like to do is write a for loop that spawns multiple threads. The threads must call a certain function multiple times. So in other words I need each thread to call the same function on different objects. How can I do this using std::thread c++ library?
You can simply create threads in a loop, passing different arguments each time. In this example, they are stored in a vector
so they can be joined later.
struct Foo {};
void bar(const Foo& f) { .... };
int main()
{
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i)
threads.push_back(std::thread(bar, Foo()));
// do some other stuff
// loop again to join the threads
for (auto& t : threads)
t.join();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With