有没有一种方法可以为类的每个对象提供一个boost线程

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

本文关键字:对象 boost 线程 一个 方法 一种 有没有      更新时间:2023-10-16

在我的代码中,我想创建一组类的对象,然后给每个对象一个单独的线程,这样对象都可以同时执行操作。

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

我想做一些类似上面代码的事情。如果是这样的话,代码就不会编译,但这是我想要的总体想法。有人知道怎么做我想做的事吗?

感谢

以下代码应在C++11中工作,并并行执行多个Worker::foo()

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

如果你相信你的元素引用仍然有效,你甚至可以不使用唯一的指针:

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