Intel® oneAPI Threading Building Blocks
Ask questions and share information about adding parallelism to your applications when using this threading library.
2466 Discussions

Why const Body in parallel_for implementation?

AJ13
New Contributor I
247 Views
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
Alexey-Kukanov
Employee
247 Views

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.

0 Kudos
Reply