C++11 多线程,通过引用传递
c++11 multithread, passing by reference
void _function_(std::vector<long long>& results){
results.push_back(10);
return ;
}
int main(){
std::vector<std::thread> threads;
std::vector<std::vector<long long>> results_array;
for(int i=1;i<=N;i++){
results_array[i]=std::vector<long long>();
threads.push_back(std::thread(&_function_,results_array[i]));
}
for(auto& th : threads){
th.join();
}
return 0;
}
这是 c++ 代码。我想使用std::vector<long long>
来保留每个线程的结果。所以我初始化了一个 每个线程std::vector<std::vecotor<long long>>
。但是,在通过results_array[i]
时,我遇到了以下错误:
In file included from /usr/include/c++/5/thread:39:0,
from multi-thread.cc:3:
/usr/include/c++/5/functional: In instantiation of ‘struct std::_Bind_simple<void (*(std::vector<long long int>))(std::vector<long long int>&)>’:
/usr/include/c++/5/thread:137:59: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (*)(std::vector<long long int>&); _Args = {std::vector<long long int, std::allocator<long long int> >&}]’
multi-thread.cc:21:60: required from here
/usr/include/c++/5/functional:1505:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::vector<long long int>))(std::vector<long long int>&)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/5/functional:1526:9: error: no type named ‘type’ in ‘class std::result_of<void (*(std::vector<long long int>))(std::vector<long long int>&)>’
_M_invoke(_Index_tuple<_Indices...>)
我也尝试std::ref(results_array[i])
,但有恶化错误。
任何人都可以在这个问题上帮助我吗?谢谢!
这里有正确的代码:
void _function_(std::vector<long long>& results){
results.push_back(10);
return ;
}
int main(){
int N = 10;
std::vector<std::thread> threads;
std::vector<std::vector<long long>> results_array;
for(int i=0;i<N;i++){
results_array.push_back(std::vector<long long>());
threads.push_back(std::thread(&_function_, std::ref(results_array[i])));
}
for(auto& th : threads){
th.join();
}
return 0;
}
您的问题出在以下行:
threads.push_back(std::thread(&_function_, std::ref(results_array[i])));
你没有得到results_array的参考。 哟也必须像这里一样纠正
results_array.push_back(std::vector<long long>());
相关文章:
- 在C++中使用cURL和多线程
- 多线程双缓冲区
- 为什么我的多线程作业队列崩溃
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 为什么一个向量上的多线程操作很慢
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 全局变量 多读取器 一个写入器多线程安全?
- boost::文件系统::recursive_directory_iterator多线程安全
- 如何阻止TensorFlow的多线程
- 如何在多线程中正确使用unique_ptr进行多态性?
- 并发/多线程:是否可以以这种方式生成相同的输出?
- C++11 多线程,通过引用传递
- 通过引用和多线程传递对象
- 如何在类中进行 c++ 多线程处理(将线程引用保留为成员 var)
- 引用计数类和多线程
- 通过引用使用参数进行 C++ 多线程函数调用
- C++引用从多线程返回值
- 多线程 - 为什么在引用上工作不会改变它,而在指针上工作正常
- 多线程应用程序中对象的引用计数