Search code examples
parallel-processingc++17g++

Why std::execution::par_unseq doesn't work?


What could be a reason the following code doesn't run parallel ?

#include <iostream>
#include <execution>
#include <unistd.h>

int main() {
    std::vector<int> parts(10);
    std::iota(parts.begin(), parts.end(), 0);

    std::for_each(std::execution::par_unseq,
                  parts.begin(), parts.end(), [&](int part) {
        usleep(1'000'000);
        std::cout << part << std::endl;
    });

    return 0;
}

This is Linux Debian running on AMD and the code is compiled by the following command

g++ -std=c++17 -fopenmp -O2 -o test test.cpp

The code should output the numbers 0..9 within about 1 second. Now it takes about 10 seconds because the code doesn't run parallel.

Btw. The usleep() function can be replaced by some other calculation heavy function but it doesn't change the situation.

EDIT:

I did "sudo apt install libtbb-dev" and then compiled with -ltbb which must be the latest parameter in compilation command or it doesn't work. Problem solved. Thank you @Ted Lyngmo !


Solution

  • The parallel execution policies describes the kinds of parallelism allowed.

    The implementation is allowed to fallback on a sequential execution policy if a parallel one is not implemented, which seems to be the case for you. In terms of implementation details, it could look like this in the header file:

    #ifdef __has_some_parallel_backend
    use_parallel_backend(first, last);
    #else
    use_sequential_fallback(first, last);
    #endif
    

    Some implementations can conditionally use these parallel policies depending on what additional packages you've got installed.