有没有一种方法可以为类的每个对象提供一个boost线程
Is there a way to have a boost thread per object of a class?
在我的代码中,我想创建一组类的对象,然后给每个对象一个单独的线程,这样对象都可以同时执行操作。
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()));
}
相关文章:
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- 从 Boost ASIO 获取 epoll 描述符 io_service对象
- 将 boost 序列化对象的 asio::streambuf 表示转换为 Beast 的 DynamicBody req.body()
- 如何将来自 Boost.Python 的map_indexing_suite与自定义而不是标准对象一起使用?
- 如何复制 boost::aligned_storage 对象中的数据?
- 释放 boost::singleton_pool 中的所有对象
- 如何从 boost::container::vector<std::string>::iterator 访问索引和对象?
- 在 boost::heap::p riority_queue 中推送结构对象时出错
- 如何将任何值转换为对象并使用 boost::p roperty_tree json 添加成员
- 动态分配许多 Boost::直方图对象
- 在 boost::p ython 中的 python 对象中运行 python 代码
- 将动态分配对象传递到 boost::any 构造函数中
- 通过 Boost Python 在C++对象之间传递共享指针的隔离错误
- Boost.Python 返回引用现有 c++ 对象的 python 对象
- 使用BOOST :: PYTHON返回裸露的类对象列表,这些对象是不可复制的
- 重用 Boost 的计时器对象
- 使用boost :: python手动构建共享对象
- 如何在Boost Serialization中检索多个对象值
- Boost Intervocess:通过迭代通过从结构引用对象的映射进行迭代时
- OPENCL:可以将模板对象作为内核参数,并使用boost :: Compute