Functions in parallel_for body

Functions in parallel_for body


I have a liitle question about having function declarations inside a parallel_for body.

Here's the code:

#include "tbb/blocked_range.h"
#include "tbb/parallel_for.h"
#include "tbb/partitioner.h"
#include <iostream>
#include <vector>
class Do{
  std::vector< std::vector<unsigned int> >* lv;
  Count(const std::vector<unsigned int>& v) {
    int c(0);
    for(int i=0;i<v.size();++i) ++c;
  Do(std::vector< std::vector<unsigned int> >* lv_):lv(lv_){}
  void operator()(const tbb::blocked_range<unsigned int>& r) const {
    for(unsigned int i=r.begin();i<r.end();++i) {
//      unsigned int place(i);
      for(unsigned int k(0); k<10; ++k){
      int cnt(0);
int main(int argc, char* argv[]) {
  std::vector< std::vector<unsigned int> > gv;
  tbb::parallel_for(tbb::blocked_range<unsigned int>(0,2),Do(&gv),tbb::auto_partitioner());
  for(unsigned int i(0);i<2;++i) {
    std::cout << "Line " << i << ": ";
    for(unsigned int j(0);j<gv[i].size();++j){
      std::cout << gv[i][j] << " ";
    std::cout << "n";
  return 0;

When compiling this code, I get the error message In member function ‘void Do::operator()(const tbb::blocked_range<unsigned int>&) const’:
error: passing ‘const Do’ as ‘this’ argument of ‘int Do::Count(const std::vector<unsigned int, std::allocator<unsigned int> >&)’ discards qualifiers.

My question is why that happens. Why can't I call Count from the parallel_for loop?.

Thanks in advance.

3 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.
Best Reply


Why can't I call Count from the parallel_for loop?

Making Count() const (like the operator()) will get rid of the error message, but it will still be your responsibility to do something useful of course. For the purpose of counting, you would probably be better off with parallel_reduce(): parallel_for() has no well-defined way to return state to the caller, and thread-safe manipulation of a shared object passed by reference through the Body instance is typically slower than recursive reduction. Locking down the Body instance in parallel_for() makes that clear at build time, to help prevent simple mistakes, e.g., not realising that parallel_for() may unpredictably make copies of the Body or reuse the same instance.

Ok, thanks. The Count function is just an example, I don't plan to use a counter in there :)

Leave a Comment

Please sign in to add a comment. Not a member? Join today