I have started delving into Multi-threading and I am currently reading the C++ Concurrency in Action book.
On chapter 2 (Managing threads, p. 24), the author explains the usage of std::ref
when passing in variables that are required to be passed in by reference.
He also explains that not using the std::ref
to wrap your variable, the function on that thread will act upon the locally stored variable (due to the copy).
Naturally, I wanted to try both and I intentionally passed the argument without the std::ref
...
However, the following code does not compile on either clang, g++, vc++. I also used both -std=c++11
and -std=c++14
to make sure there is no language update that could have affected it.
void updatePos(double &pos_)
{
pos_ = 12.5;
}
int main()
{
double position = 0.0;
std::thread pos_thread(updatePos,position); // does not compile
pos_thread.join();
std::cout<< "Position: " << position <<std::endl;
}
Online code example: https://rextester.com/IDQGG96391
The compiler error from clang is:
/usr/include/c++/v1/thread:337:5: error: attempt to use a deleted function __invoke(_VSTD::move(_VSTD::get<0>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...); ^ /usr/include/c++/v1/thread:347:5: note: in instantiation of function template specialization 'std::__1::__thread_execute' requested here __thread_execute(*__p, _Index()); ^ /usr/include/c++/v1/thread:359:42: note: in instantiation of function template specialization 'std::__1::__thread_proxy
' requested here int __ec = pthread_create(&__t_, 0, &__thread_proxy<_Gp>, __p.get()); ^ source_file.cpp:15:17: note: in instantiation of function template specialization 'std::__1::thread::thread' requested here std::thread pos_thread(updatePos,position); // does not compile ^ /usr/include/c++/v1/type_traits:1069:5: note: '~__nat' has been explicitly marked deleted here ~__nat() = delete;
The book mentions that the way the std::thread
constructor works, is similar to std::bind
.
Has something changed in the language or am I doing something horribly wrong?