0

好的新尝试,

我将我的代码从正常更改vector<Individual>vector<shared_ptr<Individual>>. 从那以后,我的线程代码不起作用,我不知道如何修复它。Start() 是 Individual 的 void 成员,但是如果只有指向它们的指针,我该如何称呼它?

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();
}

当我将它改回向量和非并行版本时,它可以工作:

 for (int i=0;i<(int)Individuals.size();i++) {
    Individuals.at(i)->start();
}

像魅力一样工作,也是。所以我认为线程 push_back 有问题?错误消息(粗略翻译)是:

 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]

多谢你们

4

1 回答 1

1

试试这个 :

threads.push_back(thread(&Individual::start,Individuals.at(i).get()));

shared_ptr您可以通过withget方法访问指针保持。但是,您应该确保shared_ptr在加入所有线程之前不要处理 this 的所有实例,否则它们将有一个悬空指针Individual.

于 2012-12-24T06:33:25.103 回答