Reputation: 13
ok new try,
i changed my code from a normal vector<Individual>
to vector<shared_ptr<Individual>>
. since that, my threading code doesn't work and i don't have a clue on how to fix it. Start() is a void member of Individual, but how do i call it if there are only pointers to those?
std::vector<thread> threads;
for (int i=0;i<(Individuals.size()-howManyChampions-howManyMutations);i++) {
threads.push_back(thread(&Individual::start,&Individuals.at(i)));
if (threads.size() % 5 == 0) {
for(auto& thread : threads){
thread.join();
}
threads.clear();
}
}
for(auto& thread : threads){
thread.join();
}
it works when i change it back to just vector and the non-parallel version:
for (int i=0;i<(int)Individuals.size();i++) {
Individuals.at(i)->start();
}
works like a charm, too. So i assume there is something wrong at the thread push_back? error messages (roughly translated) are:
instance created from »_Res std::_Mem_fn<_Res (_Class::*)(_ArgTypes ...)>::operator()(_Tp&, _ArgTypes ...) const [mit _Tp = std::shared_ptr<Individual>*, _Res = void, _Class = Individual, _ArgTypes = {}]«|
instance created from »void std::_Bind_result<_Result, _Functor(_Bound_args ...)>::__call(std::tuple<_Args ...>&&, std::_Index_tuple<_Indexes ...>, typename std::_Bind_result<_Result, _Functor(_Bound_args ...)>::__enable_if_void<_Res>::type) [mit _Res = void, _Args = {}, int ..._Indexes = {0}, _Result = void, _Functor = std::_Mem_fn<void (Individual::*)()>, _Bound_args = {std::shared_ptr<Individual>*}, typename std::_Bind_result<_Result, _Functor(_Bound_args ...)>::__enable_if_void<_Res>::type = int]«|
instance created from »std::_Bind_result<_Result, _Functor(_Bound_args ...)>::result_type std::_Bind_result<_Result, _Functor(_Bound_args ...)>::operator()(_Args&& ...) [mit _Args = {}, _Result = void, _Functor = std::_Mem_fn<void (Individual::*)()>, _Bound_args = {std::shared_ptr<Individual>*}, std::_Bind_result<_Result, _Functor(_Bound_args ...)>::result_type = void]«|
instance created from »void std::thread::_Impl<_Callable>::_M_run() [mit _Callable = std::_Bind_result<void, std::_Mem_fn<void (Individual::*)()>(std::shared_ptr<Individual>*)>]«|
instanziiert von hier|
Pointer to element type »void (Individual::)()« with Objecttype »std::shared_ptr<Individual>« incompatible
Return-Command with value in »void« returning Function [-fpermissive]
thanks guys
Upvotes: 0
Views: 1015
Reputation: 465
Try this :
threads.push_back(thread(&Individual::start,Individuals.at(i).get()));
You can access the pointer hold by a shared_ptr
with get
method. However you should make sure that you do not dispose all instances of this shared_ptr
before you join all threads or else they will have a dangling pointer of Individual
.
Upvotes: 1