使用指针向量创建线程
creating threads using vector of pointers
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
。
相关文章:
- C++使用params创建线程函数会导致转换错误
- 为什么我不能在 while 循环中创建线程?
- 如何创建线程序列以按照启动顺序执行任务?
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- std::使用类成员函数创建线程 - 最佳实践
- CPP:如何使用需要指针的方法创建线程
- 使用 lambda 表达式创建线程时,如何为每个线程提供自己的 lambda 表达式副本
- C++,如何创建线程限制/受保护的变量和函数
- BOOST_LOG_SEV在创建线程后损坏async_read_some
- 为什么当我在构造函数中创建线程时,实例化对象和对象的指针的行为不同
- 如何通过调用类中的函数来创建线程
- 如何在Silverlight本机C 中创建线程
- 通过类构造函数创建线程
- C++:创建线程时出现问题;错误 C2672:"std::invoke":找不到匹配的重载函数
- 尝试在dll main中创建线程
- 如何在Linux上为C和C 创建线程安全LIB
- 如何在 dll 中创建线程 (c++)?
- 从调度队列块 [ swift / c++ ] 创建线程
- 从成员类功能创建线程
- 创建线程,但不要立即在 Linux 中运行它