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

reference to gateway_t from async_node

liu__chia-lun
Beginner
868 Views

In the following code snippet copied from https://github.com/Apress/pro-TBB/blob/master/ch18/fig_18_03.cpp, I have a question about the validity of function parameter gateway.

How can I guarantee that it is safe to access gateway in the following thread function. My concern is that if flow graph gets reclaimed on exception, I think it becomes unsafe to access gateway and asyncThread does not know that.

 

void run(int input, gateway_t& gateway) {

gateway.reserve_wait();

asyncThread = std::thread{

[&,input]() {

std::cout << "World! Input: " << input << '\n';

int output = input + 1;

gateway.try_put(output);

gateway.release_wait();

}

};

}

 

chialun

0 Kudos
1 Solution
Aleksei_F_Intel
Employee
867 Views

Hi chialun,

Of course it is unsafe to access any variable after it has undergone destruction. Thus, the question is not specific to the flow graph and boils down to how to make sure the variable, which is created on the first thread, still exists while being accessed on the second thread. 

The obvious solution is to use heap memory instead of the stack memory for holding the graph along with its nodes, so once the exception is thrown necessary variables are not destroyed. However, the disadvantage of this is to track now when to delete that heap memory.

-Aleksei

View solution in original post

0 Kudos
2 Replies
Aleksei_F_Intel
Employee
868 Views

Hi chialun,

Of course it is unsafe to access any variable after it has undergone destruction. Thus, the question is not specific to the flow graph and boils down to how to make sure the variable, which is created on the first thread, still exists while being accessed on the second thread. 

The obvious solution is to use heap memory instead of the stack memory for holding the graph along with its nodes, so once the exception is thrown necessary variables are not destroyed. However, the disadvantage of this is to track now when to delete that heap memory.

-Aleksei

0 Kudos
Alexei_K_Intel
Employee
867 Views

gateway.reserve_wait() prolongs graph::wait_for_all until gateway.release_wait() is called even in a case of exception and cancellation of the graph execution. In other words, if an exception is occurred, graph will wait for gateway.release_wait() in any case. I.e. it is safe to access gateway if you can guarantee that it is reserved with the reserve_wait method.

0 Kudos
Reply