gpt4 book ai didi

multithreading - 排队任务时减少堆分配数

转载 作者:行者123 更新时间:2023-12-03 13:00:13 26 4
gpt4 key购买 nike

堆分配是我的应用程序中的瓶颈,在向我的线程池发送小任务时,我想避免它们。

我可以将std::packaged_task与堆栈分配器一起使用吗?在什么条件下?这种选择的优点/缺点是什么?是否有更好的选择来避免运算符(operator)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();
}

最佳答案

您的“在堆栈超出范围之前,我可能需要阻塞”注释清楚地标识了这里的唯一问题。您唯一必须确保的是,由于发送线程堆栈中的任务必须一直保留在该线程中,直到您的线程池执行该任务为止。

除此之外,使用堆栈而不是堆分配没有问题。

关于multithreading - 排队任务时减少堆分配数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25750408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com