Intel® Moderncode for Parallel Architectures
Support for developing parallel programming applications on Intel® Architecture.
1698 Discussions

In oneTBB flowgraph, destructor is called more times than constructor when using function_node.

Kohn-Sham
New Contributor I
608 Views

Hi. 

I'm revising the example.

https://oneapi-spec.uxlfoundation.org/specifications/oneapi/v1.3-rev-1/elements/onetbb/source/flow_graph/message_flow_graph_example

 

But I noticed that for a function object, constructor is called once and destructor is called multiple times when it is used as argument of Body in function_node.

 

For example, 

class sum {
  int &my_sum;
public:
sum() { std::cout << "constructor" << std::endl; }
  ~sum() { std::cout << "destructor" << std::endl; } sum( int &s ) : my_sum(s) {} int operator()( std::tuple<int, int> v ) { my_sum += get<0>(v) + get<1>(v); return my_sum; } };

// ... some codes ... //
int main() {
// ... some codes ... //
function_node<std::tuple<int,int>,int> summer( g, serial, sum(result) );
}

 

In this code, constructor and destructor of sum is called at construction of function_node object (summer).

After that when the flowgraph is finished, destructor of sum is called triple times.

 

This may be problem if class sum has resource (pointer), because it will trying to dangling pointer.

To avoid this problem, I replace the usage of function_node as follow.

  sum sum_obj(result);
function_node<std::tuple<int,int>,int> summer( g, serial, std::ref(sum_obj) );

 

For this problem, the question is 

 1. Is it intended operation of function_node? (calling destructor more than constructor.)

 2. How to use function_node for the function object which has resource? (and how about my solution above?)

 

Thank you for reading.

0 Kudos
1 Reply
Kohn-Sham
New Contributor I
574 Views

I'm sorry for this simple problem, but I found another solution.

 : Define the function object copy constructor correctly if resource is in member.

So, the both problems are solved I think.

 1. Fuction object have to copied for flowgraph operation. (maybe to each worker) So, it is intended. 

 2. It depends. If it is allowed for each thread for sharing the common resource, std::ref solution will be good.

0 Kudos
Reply