如何使用新的 C++17 执行策略?

How do I use the new C++17 execution policies?

我正在阅读 std::algorithm documentation at cppreference.com and I noticed a C++17 tag on a lot of cool things I haven't used yet. What got my attention most was the new execution policies. 我从阅读中收集到的信息是,我可以通过指定执行策略来创建任何我想要的多线程循环。

例如,我有一个程序可以输出带有二维图形的图像。

int main(){
    std::for_each(
        img.buffer().begin(),
        img.buffer().end(),
        renderer(
            {-0.5, 0.0, 2.666, 2.0, M_PI / 2.0, 0.0},
            img,
            16
        )
    );
    fout << img;
}

如果我想让这个程序成为多线程的,我应该可以用一行来完成。

int main(){
    std::for_each(
        std::execution::par_unseq, // c++17 feature
        img.buffer().begin(),
        img.buffer().end(),
        renderer(
            {-0.5, 0.0, 2.666, 2.0, M_PI / 2.0, 0.0},
            img,
            16
        )
    );
    fout << img;
}

然而,当我第一次尝试这个(使用 g++ -std=c++17)时,我得到一个错误告诉我 ‘std::execution’ has not been declared,所以我尝试添加 #include <execution>,但它显示 execution: No such file or directory。我也试过 #include<experimental/algorithm> 而不是 #include<algorithm> 但我得到了相同的结果。如何使用这个新功能?

尚未最终确定。而各种编译器还没有完全实现

-std=c++17 表示 "give me all of C++17 you have finished",而不是 "be a perfectly valid C++17 compiler"。

您的编译器 and/or 标准库目前不支持此功能。请过几天再回来查看 weeks/months/years。

没有普遍接受的 "please give me C++17 if you fully support it, and otherwise give me an error" 标志可以传递给编译器;部分原因是它几乎没有实际用途。如果他们提供的 C++17 子集足够,那么你就赢了。如果您需要一个完全兼容的编译器,特定版本的编译器不知道它们是否有错误,因此您无论如何都不能信任该标志,并且必须针对编译器版本对其进行测试。如果您已经知道哪些版本的编译器具有足够有效的 C++17,则不需要标志来告诉您。

据我了解cppreference 此功能在文档 P0024R2 中定义,但尚未在任何编译器中得到支持。

如果您使用的是 g++,那么您可以尝试非标准扩展:

https://gcc.gnu.org/onlinedocs/libstdc++/manual/parallel_mode.html

对于 Microsoft 编译器:请参阅 C++17 Progress in VS 2017 15.5 and 15.6 您将在其中找到:

Status  Std   Paper   Title
Partial C++17 P0024R2 Parallel Algorithms

对于 GCC,Fanael wrote in his , see Table 1.5. C++ 2017 Implementation Status at https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2017 你会在哪里找到

Library Feature                             Proposal    Status
The Parallelism TS Should be Standardized   P0024R2     No