You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Windows迁移Linux(Ubuntu)项目:ppl.h的parallel_for替代方案咨询

在Ubuntu上替代PPL的parallel_for的方案

我来帮你解决这个问题——从Windows的PPL迁移到Ubuntu上替代parallel_for的方案有几个,都是成熟可靠的,我给你详细讲讲:

1. 使用C++标准库的<execution>并行算法(推荐)

从C++17开始,标准库引入了并行执行策略,你可以用它实现和parallel_for一样的并行循环效果,而且完全跨平台,不需要依赖第三方库(不过GCC的实现需要链接TBB,后面会说明)。

如果你原来的PPL代码是这样的:

#include <ppl.h>

parallel_for(0, 100, [](int i) {
    // 你的处理逻辑
});

可以改成用标准库的std::for_each配合并行策略:

#include <execution>
#include <algorithm>
#include <vector>
#include <numeric> // 用于std::iota

int main() {
    // 生成0到99的索引数组
    std::vector<int> indices(100);
    std::iota(indices.begin(), indices.end(), 0);

    // 使用并行执行策略遍历
    std::for_each(std::execution::par, indices.begin(), indices.end(), [](int i) {
        // 你的处理逻辑
    });

    return 0;
}

如果你的编译器支持C++20,还可以用std::views::iota简化索引生成,不用手动创建vector:

#include <execution>
#include <algorithm>
#include <ranges>

int main() {
    std::ranges::for_each(std::views::iota(0, 100), std::execution::par, [](int i) {
        // 你的处理逻辑
    });

    return 0;
}

编译的时候需要指定C++版本并链接TBB:

g++ your_code.cpp -o your_program -std=c++17 -ltbb
# 或者C++20
g++ your_code.cpp -o your_program -std=c++20 -ltbb

2. 使用Intel TBB库(迁移成本最低)

PPL和Intel TBB都是Intel推出的并行库,两者的API非常相似,tbb::parallel_for几乎可以直接替换PPL的parallel_for,迁移成本极低。

步骤如下:

  1. 先在Ubuntu上安装TBB库:
sudo apt install libtbb-dev
  1. 修改代码:把#include <ppl.h>替换成#include <tbb/parallel_for.h>,原来的parallel_for调用几乎不用改,只需要加上tbb::命名空间(或者用using namespace tbb;):
#include <tbb/parallel_for.h>

int main() {
    tbb::parallel_for(0, 100, [](int i) {
        // 你的处理逻辑
    });

    return 0;
}
  1. 编译时链接TBB库:
g++ your_code.cpp -o your_program -ltbb

3. 使用OpenMP(简单易用)

OpenMP是一个广泛使用的并行编程模型,通过编译指令实现并行循环,写法非常直观,适合快速改造现有代码。

步骤如下:

  1. Ubuntu的GCC默认已经支持OpenMP,不需要额外安装库,直接修改代码:
#include <omp.h>

int main() {
    #pragma omp parallel for
    for (int i = 0; i < 100; ++i) {
        // 你的处理逻辑
    }

    return 0;
}
  1. 编译时加上-fopenmp参数:
g++ your_code.cpp -o your_program -fopenmp

最后给点小建议

  • 如果追求跨平台兼容性,优先选C++标准库的并行算法,以后换其他平台也不用改代码;
  • 如果想最小化代码修改量,直接用Intel TBB,几乎无缝迁移;
  • 如果只是简单的循环并行,OpenMP是最快上手的选择。

内容的提问来源于stack exchange,提问作者kangfox

火山引擎 最新活动