首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >std::线程的分割故障

std::线程的分割故障
EN

Stack Overflow用户
提问于 2015-11-14 21:27:06
回答 1查看 2.4K关注 0票数 0
代码语言:javascript
复制
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;
};

所以我有一个函数调用:

代码语言:javascript
复制
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();
}

下两个函数: funct是逆亚像素

代码语言:javascript
复制
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);
    }
}

主要内容:

代码语言:javascript
复制
pppm_color_pixel(p,out, &inverse_subpixel,pppm_get_max_cores());

问题是,当我运行这个程序时,它会显示一个分段错误。这种情况发生在这条线上:

代码语言:javascript
复制
iterator[i].green = func(iterator[i].green);

我真正不明白的是,当这种情况发生时,i = 2或更多。它从第一次开始就不会崩溃。即使我只调用一个线程,结果也是一样的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-14 21:50:39

pppm_color_chunk_pixel接受ppm_pixel的副本。由于它是由值复制的,将*iterator传递给它只会导致一个元素被复制。在&start_pixel之后迭代任何东西都会失败。由于std::thread不通过引用传递对象,为此还需要一个引用包装器。

代码语言:javascript
复制
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);
}

称之为:

代码语言:javascript
复制
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];
}

我还没有测试过,但我想这是你的问题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33713571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档