Reputation: 41
I have a problem with threads in C++. I want to create threads consisting of class member method with a specific object assigned. What is more, an object of another user-defined class is passed to that method. Please find the code below:
Grid an_chan(NX, NY, xmax, ymax);
an_chan.calc_paraFlow(anode);
Grid *ptr_grid = &an_chan;
Variable T(Tin, Tinit, lambda_m, rho_m, Cp_m);
Variable *ptr_T = &T;
std::thread first (&Variable::initialize, ptr_T, ptr_grid);
first.join();
Here is the initialize method prototype:
void Variable::initialize(Grid& grid_obj)
Before I tried to add the thread, everything worked just right.
I am just wondering if this is not a compiler issue? Maybe something is wrong with my code I can not notice? Any possible fixes? Below I included the error returned by the compiler. As you can see I am using TDM GCC 5.1.0. I was using it with threads before and everything was working quite ok.
In file included from C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/thread:39:0, from main.cpp:13: C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/functional: In instantiation of 'struct std::_Bind_simple(chal::Variable, chal::Grid)>': C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/thread:142:59: required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (chal::Variable::*)(chal::Grid&); _Args = {chal::Variable&, chal::Grid&}]' main.cpp:45:61: required from here C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/functional:1505:61: error: no type named 'type' in 'class std::result_of(chal::Variable, chal::Grid)>' typedef typename result_of<_Callable(_Args...)>::type result_type; ^ C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/functional:1526:9: error: no type named 'type' in 'class std::result_of(chal::Variable, chal::Grid)>' _M_invoke(_Index_tuple<_Indices...>)
Upvotes: 0
Views: 1076
Reputation: 17
As @acraig5075 mentioned:
The second parameter to the std::thread constructor should be a pointer to the object. You're dereferencing ptr_T.
After this you might also want to bind the function before passing to thread:
std::thread first(std::bind(&Variable::initialize, ptr_T, *ptr_grid));
Upvotes: -1
Reputation: 10756
As your initialize
function takes it's parameter by reference you should wrap the argument in std::ref
.
std::thread first(&Variable::initialize, ptr_T, std::ref(*ptr_grid));
Upvotes: 2