将数组作为参数传递给std::thread
Passing array as argument to std::thread
我很难使用std::thread
将整数数组传递给函数。线程似乎不喜欢它的数组部分。还有什么其他方法可以将数组传递给线程函数?
#include <thread>
#include <ostream>
using namespace std;
void process(int start_holder[], int size){
for (int t = 0; t < size; t++){
cout << start_holder[t] << "n";
}
}
int main (int argc, char *argv[]){
int size = 5;
int holder_list[size] = { 16, 2, 77, 40, 12071};
std::thread run_thread(process,holder_list,size);
//std::ref(list) doesnt work either
//nor does converting the list to std::string then passing by std::ref
run_thread.join();
}
由于您使用C++,请开始使用std::vector或std::list,而不是C样式数组。还有许多其他类型的容器。如果您想要一个固定大小的数组,请使用std::array(从C++11开始)。
这些容器具有获取大小的函数,因此不需要将其作为单独的参数发送。
#include <thread>
#include <iostream>
#include <vector>
void process(std::vector<int> start_holder){
for(int t = 0; t < start_holder.size(); t++){
std::cout << start_holder[t] << "n";
}
// Or the range based for
for(int t: start_holder) {
std::cout << t << "n";
}
}
int main (int argc, char *argv[]){
std::vector<int> holder_list{ 16, 2, 77, 40, 12071};
std::thread run_thread(process, holder_list);
run_thread.join();
}
使size
常数:
#include <thread>
#include <iostream>
void process(int* start_holder, int size){
for (int t = 0; t < size; t++){
std::cout << start_holder[t] << "n";
}
}
int main (int argc, char *argv[]){
static const int size = 5;
int holder_list[size] = { 16, 2, 77, 40, 12071};
std::thread run_thread(process, holder_list, size);
run_thread.join();
}
如果size
是可变的,则int arr[size]
不是标准C++。正如编译器在错误中所说,它是该语言的变量数组扩展,与int*
(也称为int []
)不兼容。
相关文章:
- 在std::thread中,joinable()然后join()线程安全吗
- 分离一个静态常量 std::thread?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 如何从 std::thread 返回值
- 将 std::thread by 值推送到列表中
- 转发变量参数列表以模拟 std::thread
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- std::thread 增加 DLL 引用计数,从而防止卸载 DLL
- 如何防止 std::thread 在 QT 中冻结 GUI?
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- 为什么参数在构造 std::thread 时移动两次
- std::thread::_Invoker 使用线程编程时出错
- 在线程 A 中创建一个 std::thread 对象,在线程 B 中连接
- 为什么编译器抱怨 std::thread 参数在转换为右值后必须是可调用的?
- ZeroMQ 在使用 std::thread 创建工作线程时崩溃
- 在没有复制构造函数的对象的成员函数中启动 std::thread
- CLang:在 std::thread 中运行函数会导致结构创建BAD_ACCESS
- 调用以CWinThread为基的类运算符()的std::thread失败
- 如何通过std::thread生成多个线程
- std::future::get()或std::future::wait()是std::thread::join()的替