将2-Dim循环拆分为多个线程

Splitting 2-Dim loop into multiple threads

本文关键字:线程 拆分 2-Dim 循环      更新时间:2023-10-16

我的算法通过使用在U和V段上迭代的二维循环来计算三维空间中形状的顶点。

for (LONG i=0; i < info.useg + 1; i++) {
    // Calculate the u-parameter.
    u = info.umin + i * info.udelta;
    for (LONG j=0; j < info.vseg + 1; j++) {
        // Calculate the v-parameter.
        v = info.vmin + j * info.vdelta;
        // Compute the point's position.
        point = calc_point(op, &info, u, v);
        // Set the point to the object and increase the point-index.
        points[point_i] = point;
        point_i++;
    }
}

然而,点的数组是一维数组,这就是为什么point_i在每个循环中递增的原因。我知道我可以通过point_i = i * info.vseg + j来计算索引。

我希望这个循环是多线程的。我的目标是创建多个线程,所有线程都处理特定范围的点。在线程中,我会这样做:

for (LONG x=start; x <= end; x++) {
    LONG i = // ...
    LONG j = // ...
    Real u = info.umin + i * info.udelta;
    Real v = info.vmin + j * info.vdelta;
    points[i] = calc_point(op, &info, u, v);
}

问题是从线性点指数计算ij指数。当(我认为):时,我如何计算ij

point_i = i * vsegments + j

我不会解数学题,这里。。

point_i = i * vsegments + j为您提供:

i = point_i / vsegments
j = point_i % vsegments

当然,您的循环实际上每个都进行segments + 1次迭代(索引0segments),因此您需要使用vsegments + 1而不是vsegments

顺便说一句:你真的需要把循环合并成一个多线程吗?我希望外循环通常有足够的迭代来饱和你的可用核心。