Search code examples
c++multithreadingc++11stdthread

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


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?


Solution

  • 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();
    }