Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
Beginner
8 Views

reference to gateway_t from async_node

Jump to solution

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

Accepted Solutions
Highlighted
8 Views

Hi chialun,

Jump to solution

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
Highlighted
9 Views

Hi chialun,

Jump to solution

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
Highlighted
Employee
8 Views

gateway.reserve_wait()

Jump to solution

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