Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use parallel execution policies with std::back_inserter?

Tags:

c++

c++17

I would like to know whether using execution policies std::execution::par and std::execution::par_unseq is safe when the output is std::back_insert_iterator. For example:

std::vector<std::string> src(100, "test"), dst;
std::move(std::execution::par_unseq, src.begin(), src.end(), std::back_inserter(dst));

Is it guaranteed that no concurrent insertions will be made to the destination vector?

like image 238
mentalmushroom Avatar asked Nov 24 '25 15:11

mentalmushroom


1 Answers

Calling push_back on a std::vector does not match the requirements of par_unseq or par.

So no, it isn't safe.

By saying par you are promising that access to the iterators used for input and output contains no race conditions. That fails here.

par_unseq requires more promises from you; basically that you are both data-race free, and your algorithm is suitable for vectorization (doing things in batches).

push_back does not qualify, and back_inserter is defined in terms of push_back.

On the other hand:

std::vector<std::string> src(100, "test"), dst(100, "");
std::move(std::execution::par_unseq, src.begin(), src.end(), dst.begin());

this is valid, because you are allowed to parallel and concurrently access individual elements of a vector (except vector<bool>)

like image 114
Yakk - Adam Nevraumont Avatar answered Nov 27 '25 05:11

Yakk - Adam Nevraumont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!