【问题标题】:Does global function for loop run parallel or not?循环的全局函数是否并行运行?
【发布时间】:2022-01-17 18:57:33
【问题描述】:

此代码块运行正常。但我想知道 for 循环内部是并行运行(在 cuda 中)还是串行运行?

const int xIndex = blockIdx.x * blockDim.x + threadIdx.x;
const int yIndex = blockIdx.y * blockDim.y + threadIdx.y;
int tid = yIndex * blockDim.x + xIndex;
float resultOneDimensional = 0;

if((xIndex < width) && (yIndex < height)){
    const int input_tid = yIndex * inputWidthStep + xIndex;
    const int buffer_tid = yIndex * bufferWidthStep + (xIndex * CHANNEL);
    const float readFrame = input[input_tid];
    output[buffer_tid + bufferSize] = readFrame;

    for (tid = 0; tid < CHANNEL; tid++){
         resultOneDimensional += (output[buffer_tid + bufferSize + tid] / (CHANNEL));
    }
    outputOneDimensional[input_tid] = static_cast<unsigned char>(resultOneDimensional);
}

【问题讨论】:

  • 请您使用 C 或 C++ 编程,但很少同时使用两者。您显示的代码不是有效的 C,因此请edit您的问题以删除 C 语言标签。

标签: c++ cuda


【解决方案1】:

内核的每个线程都将运行该 for 循环。

for 循环本身在单个线程的上下文中串行运行。

这意味着线程 0 将执行 for 循环的副本,线程 0 将在其 tid 值(可能为 0)处开始循环,线程 0 将执行 for 循环的主体 CHANNEL-tid次。

同样,线程 1 将执行 for 循环的副本,线程 1 将在其 tid 值(可能为 1)处开始循环,线程 1 将执行 for 循环的主体 CHANNEL-tid次。

等等,对于内核(网格)中的其他线程。

【讨论】:

  • 这段代码行在 global Cuda 函数内,所以 for 循环仍然是串行的吗?谢谢!
  • 那么如何设计这些代码来并行运行呢?
  • 是的,从您的代码中可以明显看出(例如,blockIdx.x 的用法表明这是在内核中运行的内核代码(__global__ CUDA 函数称为内核)。您的 for 循环出现进行减少。要“并行”运行其中一个,我将使用parallel reduction 方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多