难以使用 atomicMin 在矩阵中找到最小值
Difficulty using atomicMin to find minimum value in a matrix
我在使用 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;
}
harr
未分配。在调用 cudaMemcpy
之前,您应该使用 malloc
在主机端分配它。结果,您看到的打印值是垃圾。令人惊讶的是程序没有在您的机器上出现段错误。
此外,当你最后调用内核findMin
时,它的参数是harr
(根据它的名字应该是在主机端)应该在设备上执行原子操作正确。结果,当前内核调用无效。
正如@RobertCrovella 所指出的,最后缺少一个 cudaDeviceSynchronize()
调用。此外,您需要使用 cudaFree
.
释放内存
我在使用 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;
}
harr
未分配。在调用 cudaMemcpy
之前,您应该使用 malloc
在主机端分配它。结果,您看到的打印值是垃圾。令人惊讶的是程序没有在您的机器上出现段错误。
此外,当你最后调用内核findMin
时,它的参数是harr
(根据它的名字应该是在主机端)应该在设备上执行原子操作正确。结果,当前内核调用无效。
正如@RobertCrovella 所指出的,最后缺少一个 cudaDeviceSynchronize()
调用。此外,您需要使用 cudaFree
.