[英]creating threads using vector of pointers
好的新嘗試,
我將代碼從常規vector<Individual>
更改為vector<shared_ptr<Individual>>
。 從那以后,我的線程代碼不起作用,而且我不知道如何解決它。 Start()是Individual的無效成員,但是如果僅存在指向這些成員的指針,我該怎么稱呼它?
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();
}
當我將其更改回vector和非並行版本時,它將起作用:
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
指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.