标准::线程处的分段错误
Segmentation fault at std::thread
typedef struct _ppm_struct* ppm_struct;
typedef unsigned char ppm_subpixel;
typedef ppm_subpixel (*ppm_pixel_func)(ppm_subpixel);
struct ppm_pixel {
ppm_subpixel red;
ppm_subpixel green;
ppm_subpixel blue;
};
struct _ppm_struct {
unsigned int width;
unsigned int height;
unsigned int max_color;
ppm_pixel *firstpixel;
};
所以我有这个函数调用:
void pppm_color_pixel(ppm_struct p, ppm_struct out, ppm_pixel_func func, int threads) {
//ppm_pixel_func func2 = &inverse_pixel;
unsigned int w = p->width;
unsigned int h = p->height;
ppm_pixel *iterator = p->firstpixel;
std::thread th[threads];
long long total_pixels = w*h;
unsigned int count_for_thread = total_pixels/threads;
for(int j = 0; j<threads; ++j) {
th[j] = std::thread(pppm_color_chunk_pixel,func, *iterator,count_for_thread);
iterator = &iterator[count_for_thread];
}
for(int j = 0; j<threads; ++j) {
th[j].join();
}
接下来的两个功能:函数是反亚像素
ppm_subpixel inverse_subpixel(ppm_subpixel subpixel) {
subpixel = 255- subpixel;
return subpixel;
}
void pppm_color_chunk_pixel(ppm_pixel_func func, ppm_pixel start_pixel, unsigned int count) {
ppm_pixel *iterator = &start_pixel;
for(unsigned int i = 0; i< count; ++i) {
iterator[i].red = func(iterator[i].red);
iterator[i].green = func(iterator[i].green);
iterator[i].blue = func(iterator[i].blue);
}
}
主要:
pppm_color_pixel(p,out, &inverse_subpixel,pppm_get_max_cores());
问题是当我运行它时,它向我显示一个分段错误。这发生在以下行:
iterator[i].green = func(iterator[i].green);
我真正不明白的是,当这种情况发生时,i = 2
或更多。它不会从第一次崩溃。即使我尝试只调用单个线程,结果也是相同的。
>pppm_color_chunk_pixel
接受ppm_pixel
的副本。由于它是按值复制的,因此将*iterator
传递给它只会导致复制一个元素。在&start_pixel
之后迭代任何内容都将失败。由于std::thread
不通过引用传递对象,因此您还需要一个引用包装器。
void pppm_color_chunk_pixel(ppm_pixel_func func, ppm_pixel& start_pixel, unsigned int count) {
ppm_pixel* iterator = &start_pixel;
for (unsigned int i = 0; i < count; ++i) {
iterator[i].red = func(iterator[i].red);
iterator[i].green = func(iterator[i].green);
iterator[i].blue = func(iterator[i].blue);
}
调用它:
for (int j = 0; j < threads; ++j) {
th[j] = std::thread(pppm_color_chunk_pixel, func, std::ref(*iterator), count_for_thread);
iterator = &iterator[count_for_thread];
}
我还没有测试过,但我想这是你的问题。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?