Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spawn multiple threads that call same function using std::thread C++ [closed]

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?

like image 551
user2481095 Avatar asked Dec 26 '22 18:12

user2481095


1 Answers

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();
}
like image 117
juanchopanza Avatar answered Jan 11 '23 23:01

juanchopanza