Showing results for 
Search instead for 
Did you mean: 
New Contributor I

Why const Body in parallel_for implementation?

I have been looking closely at TBB internals, and implementing some of my own high-level algorithm templates (more on that later).

There is something I don't understand... what was your motivation for the user to define operator()(Range&) as a const operation? I understand that internally the body is held as a const, I would like to know the motivation.
0 Kudos
1 Reply

Citing the TBB Tutorial document:

Template function parallel_for requires that the body object have a copy constructor, which is invoked to create a separate copy (or copies) for each worker thread. It also invokes the destructor to destroy these copies. In most cases, the implicitly generated copy constructor and destructor work correctly. If they do not, it is almost always the case (as usual in C++) that you must define both to be consistent.

Because the body object might be copied, its operator() should not modify the body. Otherwise the modification might or might not become visible to the thread that invoked parallel_for, depending upon whether operator() is acting on the original or a copy. As a reminder of this nuance, parallel_for requires that the body object's operator() be declared const.