[英]parallel programming in C
我正在尝试在 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");
}
}
main2 返回一个 float ** 以便在 main 函数中按顺序打印图片。 任何人都知道为什么执行时间没有下降(例如,当它应该是相反的时候,8 个线程比 4 个线程运行的时间更长)?
添加线程还不够,还需要实际拆分任务。 看起来您在每个线程中都执行相同的工作,因此您将通过n个线程获得n个结果副本。
这里有两件事对您不利。 (1)除非您可以将线程分配给多个内核,否则您不能指望首先提高速度; 使用单个内核,无论是否并行化代码,该内核都需要完成相同的工作量。 (2)即使有多个内核,并行性能对内核上进行的计算与内核之间必要的通信量之比也非常敏感。 在循环内使用ptrhead_join()时,会产生很多这种“停止并等待另一个人”的性能下降。
动态调度: Parallelism 何时由 CPU 自动决定。 硬件尝试定位准备执行的指令
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.