@@ -49,20 +49,24 @@ using namespace RcppParallel;
4949struct InnerProduct : public Worker
5050{
5151 // source vectors
52- const double* x;
53- const double* y;
52+ const RVector< double > x;
53+ const RVector< double > y;
5454
5555 // product that I have accumulated
5656 double product;
5757
5858 // constructors
59- InnerProduct(const double* x, const double* y) : x(x), y(y), product(0) {}
59+ InnerProduct(const NumericVector x, const NumericVector y)
60+ : x(x), y(y), product(0) {}
6061 InnerProduct(const InnerProduct& innerProduct, Split)
6162 : x(innerProduct.x), y(innerProduct.y), product(0) {}
6263
6364 // process just the elements of the range I've been asked to
6465 void operator()(std::size_t begin, std::size_t end) {
65- product += std::inner_product(x + begin, x + end, y + begin, 0.0);
66+ product += std::inner_product(x.begin() + begin,
67+ x.begin() + end,
68+ y.begin() + begin,
69+ 0.0);
6670 }
6771
6872 // join my value with that of another InnerProduct
@@ -75,20 +79,22 @@ struct InnerProduct : public Worker
7579Note that ` InnerProduct ` derives from the ` RcppParallel::Worker ` class. This
7680is required for function objects passed to ` parallelReduce ` .
7781
78- Note also that we use use raw ` double * ` for accessing the vectors. This is
79- because this code will execute on a background thread where it's not safe to
80- call R or Rcpp APIs.
82+ Note also that we use the ` RVector<double> ` type for accessing the vector.
83+ This is because this code will execute on a background thread where it's not
84+ safe to call R or Rcpp APIs. The ` RVector ` class is included in the
85+ RcppParallel package and provides a lightweight, thread-safe wrapper around R
86+ vectors.
8187
8288Now that we've defined the function object, implementing the parallel inner
8389product function is straightforward. Just initialize an instance of
84- ` InnerProduct ` with pointers to the input data and call ` parallelReduce ` :
90+ ` InnerProduct ` with the input vectors and call ` parallelReduce ` :
8591
8692{% highlight cpp %}
8793// [[ Rcpp::export]]
8894double parallelInnerProduct(NumericVector x, NumericVector y) {
8995
9096 // declare the InnerProduct instance that takes a pointer to the vector data
91- InnerProduct innerProduct(x.begin() , y.begin() );
97+ InnerProduct innerProduct(x, y);
9298
9399 // call paralleReduce to start the work
94100 parallelReduce(0, x.length(), innerProduct);
0 commit comments