使用指针向量创建线程

creating threads using vector of pointers

本文关键字:创建 线程 向量 指针      更新时间:2023-10-16

ok new try,

我将代码从正常的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]

谢谢人

试试这个:

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

可以通过get方法访问shared_ptr持有的指针。然而,你应该确保在你连接所有线程之前,你没有处理这个shared_ptr的所有实例,否则它们将有一个悬挂指针的Individual