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

时间:2017-03-02 23:34:09

标签: c++ multithreading algorithm c++17

I was reading through the 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. What I gathered from reading about them is that I can make any for_each loop I want multi-threaded just by specifying an execution policy.

For example, I have a program which outputs an image with a 2D graphic on it.

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;
}

If I want to make this program multi-threaded I should be able to do it with one line.

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;
}

However when I first tried this (with g++ -std=c++17) I got an error telling me that ‘std::execution’ has not been declared, so I tried adding #include <execution> but it says execution: No such file or directory. I've also tried #include<experimental/algorithm> instead of #include<algorithm> but I get the same result. How do I use this new feature?

4 个答案:

答案 0 :(得分:11)

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

-std=c++17表示&#34;给我所有的C ++ 17你已经完成&#34;,而不是&#34;是一个完全有效的C ++ 17编译器&#34;。

此时,编译器和/或标准库不支持此功能。几周/几个月/年后再回来看看。

没有普遍接受&#34;如果你完全支持它,请给我C ++ 17,否则给我一个错误&#34; flag你可以传递给编译器;部分原因是它几乎没有实际用途。如果他们提供的C ++ 17子集足够,那么你就赢了。如果你需要一个完全兼容的编译器,特定版本的编译器不知道它们是否有错误,所以你无论如何都不能信任该标志,并且必须针对编译器版本进行测试。如果您已经知道哪些版本的编译器具有足够有效的C ++ 17,那么您就不需要一个标记来告诉您。

答案 1 :(得分:1)

据我所知cppreference 此功能在文档P0024R2中定义,并且在任何编译器中都不支持。

答案 2 :(得分:0)

如果您正在使用g ++,那么您可以尝试使用非标准扩展程序:

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

答案 3 :(得分:0)

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

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

对于GCC,正如Fanael在其comment中所写,请参阅表1.5。您可以在https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2017找到

的C ++ 2017实施状态
Library Feature                             Proposal    Status
The Parallelism TS Should be Standardized   P0024R2     No