使用执行策略和线程池有什么区别?

what is the difference between using execution policy and thread pool?

我在学习C++时遇到了这个问题

使用执行策略和 VS 使用线程池做同样的工作有什么区别?使用一个比另一个有什么好处吗?

std::atomic<int> sum{0};
std::for_each(std::execution::par_unseq, std::begin(v), std::end(v), [&](int i) {
  sum.fetch_add(i*i, std::memory_order_relaxed);
});


std::for_each(std::begin(v), std::end(v), [&](int i) {
thread_pool_->queue_work(callAddFn, i);
}

您的线程池版本正在排队 std::ranges::size(v) 小块工作,而执行策略版本被赋予决定合理块大小的自由度。

因为您指定了一个未排序的策略,所以如果 std::atomic<int>::is_lock_free() 为假,您的程序格式错误。在适当的平台上,您将获得实现它的矢量化操作。