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

tbb_thread: F is value, not reference

AJ13
New Contributor I
126 Views

Hello all.

Strange problem, I created a class to be used with tbb_thread, and I noticed that the copy constructor was being called. This doesn't make sense for my class, because I'm performing some initialization that should be done once... I was taken by surprise that the object was being copied.

Might I suggest that "F" inside of the tbb_thread templates should be F&? Thus the copy constructor won't be needed?

AJ

0 Kudos
4 Replies
RafSchietekat
Black Belt
126 Views

Like this the choice is yours to pass a proxy or perhaps even a stateless object.

RafSchietekat
Black Belt
126 Views

"Like this the choice is yours to pass a proxy or perhaps even a stateless object." With an argument specifying the state, I mean, for the second option. As for a rationale, the more prevalent use cases would otherwise be inconvenienced by requiring an argument, which here is only a possible implementation.

Alexey_K_Intel3
Employee
125 Views
We based the interface of tbb::tbb_thread on the std::thread proposal for the upcoming new C++ standard. In the proposal, std::thread takes function objects either by copy or by rvalue reference, and never by lvalue reference. In the absense of rvalue references in the current standard, our only choice was to pass it by copy.
The reasons are simple I think. Passing an object by lvalue reference is undesirable because ownership of the object is not passed this way. If the reference is non-const (i.e. modifiable), the door is opened for data races(consider the same function being passed into a few different threads) and the implementer of the function object should care about it. If the reference is const, then either the object should have the function call operator() as const, which is very restrictive, or the implementation should make a copy of the object before passing it into another thread.
robert_jay_gould
Beginner
125 Views
Quoting - Raf Schietekat

"Like this the choice is yours to pass a proxy or perhaps even a stateless object." With an argument specifying the state, I mean, for the second option. As for a rationale, the more prevalent use cases would otherwise be inconvenienced by requiring an argument, which here is only a possible implementation.

Agreed, use a reference wrapper class ifnecessary. That's what I use for other situations, not this one in particular, because normally you don't want two threads sharing F anyways,especiallyif F has state.

Reply