Intel® oneAPI Threading Building Blocks
Ask questions and share information about adding parallelism to your applications when using this threading library.
Announcements
This community is designed for sharing of public information. Please do not share Intel or third-party confidential information here.
2421 Discussions

Why const Body in parallel_for implementation?

AJ13
New Contributor I
121 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_K_Intel3
Employee
121 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.

Reply