Search code examples
c++multithreadingoopboost-thread

Is there a way to have a boost thread per object of a class?


In my code I want to create a bunch of objects of a class and then give each object a separate thread so objects can all carry out actions at the same time as each other.

for (i = 0; i < ROBOTCOUNT; i++)
{
    Robot* r = new Robot;
    boost::thread t(r);
    robotList.push_back(r);
}

I want to do something like the code above. The code doesn't compile if it's like that, but that is the general idea of what I want. Does anyone know how to do what I want?

Thanks


Solution

  • The following code should work in C++11 and executes multiple Worker::foo()s in parallel:

    #include <thread>
    #include <memory>
    #include <vector>
    
    struct Worker
    {
        void foo();
    };
    
    int main()
    {
        std::vector<std::unique_ptr<Worker>> workers;
        std::vector<std::thread>             threads;
    
        workers.reserve(N);
        threads.reserve(N);
    
        for (unsigned int i = 0; i != N; ++i)
        {
            workers.emplace_back(new Worker);
            threads.emplace_back(&Worker::foo, workers.back().get());
        }
    
        // ... later ...
    
        for (auto & t : threads) { t.join(); }
    }
    

    You could even do without the unique pointers if you trust your element references to remain valid:

    std::deque<Worker> workers;
    
    // ...
    
    for (unsigned int i = 0; i != N; ++i)
    {
        workers.emplace_back(); // pray this doesn't invalidate
        threads.emplace_back(&Worker::foo, std::ref(workers.back()));
    }