Skip to content

Instantly share code, notes, and snippets.

@asardaes
Last active January 16, 2018 20:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save asardaes/7d78af394f848a967997ff23e433c9cf to your computer and use it in GitHub Desktop.
RcppParallel segfault
class ConcreteCalculator : public Calculator
{
public:
ConcreteCalculator(const Rcpp::List& x, const Rcpp::List& y) : gcm_(nullptr) {
for (const SEXP& series : x) {
Rcpp::NumericVector this_x(series);
x_.push_back(RcppParallel::RVector<double>(this_x));
}
/* repeat for y and assign max_len_y_ */
}
~ConcreteCalculator() { if (gcm_) delete[] gcm_; }
int xLimit() const { return x_.size(); }
int yLimit() const { return y_.size(); }
double calculate(const int i, const int j) {
return this->calculate(x_[i], y_[j])
}
ConcreteCalculator* clone() const {
ConcreteCalculator* ptr = new ConcreteCalculator(*this);
ptr->gcm_ = new double[2 * (max_len_y_ + 1)];
return ptr;
}
private:
double calculate(const RcppParallel::RVector<double>& x, const RcppParallel::RVector<double>& y) {
return distance_function(&x[0], &y[0], x.length(), y.length(), gcm_);
}
std::vector<RcppParallel::RVector<double>> x_, y_;
double* gcm_;
int max_len_y_;
};
class ParallelWorker : public RcppParallel::Worker {
public:
ParallelWorker(const std::shared_ptr<Calculator>& dist_calculator,
const Rcpp::NumericMatrix& distmat)
: dist_calculator_(dist_calculator)
, distmat_(distmat)
, ncols_(dist_calculator_->yLimit())
{ }
void operator()(std::size_t begin, std::size_t end) {
mutex_.lock();
// local copy of dist_calculator so it is setup separately for each thread
Calculator* local_calculator = dist_calculator_->clone();
mutex_.unlock();
for (std::size_t i = begin; i < end; i++) {
for (int j = 0; j < ncols_; j++) {
distmat_(i,j) = local_calculator->calculate(i,j);
}
}
mutex_.lock();
delete local_calculator;
mutex_.unlock();
}
private:
const std::shared_ptr<Calculator> dist_calculator_;
RcppParallel::RMatrix<double> distmat_;
int ncols_;
tthread::mutex mutex_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment