Dávid Tóth
Dávid Tóth

Reputation: 3235

Is std::copy implemented to use multiple threads?

I would like to copy one vector into another as fast as possible.

One method is using std::copy :

std::copy(other_vector().begin(),other_vector().end(),this_vector.begin());

But since the vectors are quite long I was wondering if the std::copy function was implemented so it would use multiple threads.

I could provide a custom logic for dividing the vectors into equal disjunct parts, to copy the items separately, but I would not want to reinvent the wheel again.

So is std::copy works with multiple threads?

Upvotes: 1

Views: 1589

Answers (2)

walnut
walnut

Reputation: 22152

No, the std::copy overload you are showing in your question cannot in general be implemented to execute in parallel, because it is specified to copy elements sequentially in order from first to last. It is probably never implemented to execute in parallel under any circumstances.

Since C++17 there are parallel extensions to the standard library algorithms, which take an additional first parameter specifying an execution policy, which can be parallel, assuming the standard library implements it that way, e.g. (requires #include<execution>):

std::copy(std::execution::par, other_vector().begin(), other_vector().end(), this_vector.begin());

See cppreference.com for the different options for the execution policy and their specific meanings.

This isn't fully implemented in all compilers/standard libraries yet though and might need extra compiler options. See "Standardization of Parallelism TS" in cppreference.com's compiler support table.

Upvotes: 5

Surt
Surt

Reputation: 16099

You are in luck from C++17 you got

template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >
ForwardIt2 copy( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first );

see https://en.cppreference.com/w/cpp/algorithm/copy

Upvotes: 5

Related Questions