I am reading "C++ Concurrency in Action". I have following doubt with the below code snippet.
struct func
{
int& i;
func(int& i_):i(i_){}
void operator()()
{
for(unsigned j=0;j<1000000;++j)
{
do_something(i); //Can have issue of dangling references
}
}
};
void oops()
{
int some_local_state=0;
func my_func(some_local_state);
std::thread my_thread(my_func);
my_thread.detach();
}
The author says in order to avoid such scenario one way is to make the thread function self-contained and copy the data into the thread rather than sharing the data
I do understand the problem is because of the fact the function object created is local to the oop function and when the oops function finishes the object goes out of scope, but I cannot understand how to avoid in way author has mentioned it.
The issue is not the func
object. std::thread
will copy your functor.
First the constructor copies/moves all arguments (both the function object f and all args...) to thread-accessible storage
The issue is the reference int& i;
your functor keeps to some_local_state
which indeed will be invalid once some_local_state
runs out of scope.
To solve this copy the value of some_local_state
instead of keeping a reference to it. If you need shared access, consider using a std::shared_ptr
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments