堆分配是我的应用程序的瓶颈,我想在将小任务发送到我的线程池时避免使用它们。
我可以将std::packaged_task
与堆栈分配器一起使用吗?在哪些条件下?这个选择的优缺点是什么?是否有更好的替代方法可以避免运营商std::future
对new
共享状态的堆分配?
auto foo() {
arena<1024> buffer;
auto task = std::packaged_task<int()>{
std::allocator_arg_t,
arena_allocator{arena},
[]() -> int { return 5; }
};
auto f = task.get_future(); // is this future and its shared state stack allocated?
thread_pool.push_back(std::move(task));
// I will probably need to block before the stack goes out of scope..
return f.get();
}
答案 0 :(得分:2)
你的“我可能需要在筹码超出范围之前阻止”评论明确指出这里唯一的问题。你唯一必须确定的是,因为发送线程堆栈中的任务,它必须保持在那里直到你的线程池执行它。
除此之外,使用堆栈没有问题,而不是堆分配。