C中的并行编程

Tri*_*sha 1 c parallel-processing

我正在尝试在 C 中并行化光线跟踪器,但是随着线程数量的增加,执行时间并没有减少。我到目前为止的代码是:

main2(thread function):

float **result=malloc(width * sizeof(float*));
int count=0;
for (int px=0;, px<width; ++px)
{
     ...
     for (int py=0; py<height; ++py)
     {
         ...
         float *scaled_color=malloc(3*sizeof(float));
         scaled_color[0]=...
         scaled_color[1]=...
         scaled_color[2]=...

         result[count]=scaled_color;
         count++;
         ...
      }
}
...
return (void *) result;

main:
pthread_t threads[nthreads];
 for (i=0;i<nthreads;i++)
 {
      pthread_create(&threads[i], NULL, main2, &i);
 }

 float** result_handler;

 for (i=0; i<nthreads; i++)
 {
      pthread_join(threads[i], (void *) &result_handler);
      int count=0;

      for(j=0; j<width;j++)
     {
          for(k=0;k<height;k++)
          {
               float* scaled_color=result_handler[count];
               count ++;
               printf...
           }
           printf("\n");
       }
  }
Run Code Online (Sandbox Code Playgroud)

main2 返回一个 float ** 以便在 main 函数中按顺序打印图片。任何人都知道为什么执行时间没有下降(例如,当它应该是相反的时候,8 个线程比 4 个线程运行的时间更长)?

Eri*_*rik 6

添加线程是不够的,您还需要实际拆分任务。看起来你在每个线程中都在做同样的工作,所以你得到了 n 个线程的结果的 n 个副本。