【问题标题】:Difficulty using atomicMin to find minimum value in a matrix难以使用 atomicMin 在矩阵中找到最小值
【发布时间】:2021-04-20 20:09:26
【问题描述】:

我在使用 atomicMin 查找 cuda 矩阵中的最小值时遇到问题。我确定这与我传递给 atomicMin 函数的参数有关。 findMin 函数是要关注的函数,popmatrix 函数只是填充矩阵。

#include <stdio.h>
#include <cuda.h>
#include <curand.h>
#include <curand_kernel.h>
#define SIZE 4

__global__ void popMatrix(unsigned *matrix) {
    unsigned id, num;
    curandState_t state;
    id = threadIdx.x * blockDim.x + threadIdx.y;
    // Populate matrix with random numbers
    curand_init(id, 0, 0, &state); 
    num = curand(&state)%100;
    matrix[id] = num;

}

__global__ void findMin(unsigned *matrix, unsigned *temp) {
    unsigned id;
    id = threadIdx.x * blockDim.y + threadIdx.y;
    atomicMin(temp, matrix[id]);
    printf("old: %d, new: %d", matrix[id], temp);


}

int main() {
        dim3 block(SIZE, SIZE, 1);
    unsigned *arr, *harr, *temp;
        cudaMalloc(&arr, SIZE*SIZE*sizeof(unsigned));
        popMatrix<<<1,block>>>(arr);

    // Print matrix of random numbers to see if min number was picked right
    cudaMemcpy(harr, arr, SIZE*SIZE*sizeof(unsigned), cudaMemcpyDeviceToHost);
    for (unsigned i = 0; i < SIZE; i++) {
        for (unsigned j = 0; j < SIZE; j++) {
            printf("%d ", harr[i*SIZE+j]);
        }
        printf("\n");
    }
    temp = harr[0];
    findMin<<<1, block>>>(harr);

    
    return 0;
}

【问题讨论】:

    标签: cuda


    【解决方案1】:

    harr 未分配。您应该在调用cudaMemcpy 之前使用例如malloc 在主机端分配它。结果,您查看的打印值是垃圾。程序没有在您的机器上发生段错误,这很令人惊讶。

    此外,当你最后调用内核findMin时,它的参数是harr(它的名字应该在主机端)应该在设备上才能正确执行原子操作。因此,当前内核调用无效。

    正如@RobertCrovella 所指出的,最后缺少cudaDeviceSynchronize() 调用。此外,您需要使用cudaFree 释放内存。

    【讨论】:

    • 在最后一次内核调用之后还有should have cudaDeviceSynchronize()
    • @RobertCrovella 确实如此。这让我意识到cudaFree 也不见了。谢谢。
    • 省略cudaFree 语句可能不是好的做法,但这不是功能问题。就像在主机代码中一样,所有设备端分配都应该在拥有主机进程终止时自动释放。但是如果没有cudaDeviceSynchronize()(或类似的东西),即使其他一切都正确,您也可能看不到内核打印输出。我确实相信cudaFree 在这种用法中是一个阻塞调用,所以它可能可以用来代替cudaDeviceSynchronize()
    猜你喜欢
    • 2020-11-29
    • 2012-07-30
    • 2013-11-20
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 2019-04-25
    • 2011-10-31
    相关资源
    最近更新 更多