So that the copied variable is local to the function and all the local variable to the function is always thread safe When `const` is not used with the argument how std::thread behaves ? Therefore in order to make thread safe `std::thread` makes a copy of the variable and uses it. Because, during the execution of the thread, the passed variable to function `foo` may changed by `main` function. When `const` with argument is used, we know we are not going to modify the variable any way inside function `foo` and also compiler will not allow you to do so, then making a reference or alias to original variable may not be thread safe even though if we lock the variable. What the hell it is? Now address of both `a` and `b` is same, as soon as we remove the `const` from argument variable In order to understand this behavior we need to understand two things that how intelligently the std::thread is implemented When `const` with argument is used how std::thread behaves ? Now lets see the result after fixing the compilation error Address of variable 'a' in main is 0x7ffc6e26dab4Īddress of variable 'b' in foo is 0x7ffc6e26dab4 In this case we created a `std::ref` object and passed to the argument of function `foo` in thread. while calling in thread we need to use like below std::thread t(foo, std::ref(a)) Just we need to use `std::ref` class to convert to `rvalue`. What is `rvalue` is an another topic and discuss later. It is complaining that the value passed as a second argument to `thread` is not a `rvalue`, we need to convert to `rvalue` before sending. The important error message to observe is /usr/include/c++/9/thread:120:44: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues What the hell? We are getting compilation error. usr/include/c++/9/thread:247:2: error: no type named ‘type’ in ‘struct std::thread::_Invoker >::_result >’ usr/include/c++/9/thread:243:4: error: no type named ‘type’ in ‘struct std::thread::_Invoker >::_result >’ usr/include/c++/9/thread: In instantiation of ‘struct std::thread::_Invoker >’: usr/include/c++/9/thread:120:44: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues we all know that when we use address-of operator to the variable, then it is an alias of the original variable it points to, and shares the same address. Do you know const reference variable in c++ does not points to original variable when used in std::thread and std::async ?įrom the basics of C and C++.
0 Comments
Leave a Reply. |