使用指针向量创建线程

时间:2012-12-24 05:53:13

标签: c++ c++11

好的新尝试,

我将代码从普通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]

谢谢你们

1 个答案:

答案 0 :(得分:1)

试试这个:

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

您可以使用shared_ptr方法访问get指针。但是,您应该确保在加入所有线程之前不要释放此shared_ptr的所有实例,否则它们会有一个悬空指针Individual