CUDA集成,访问冲突

时间:2011-11-30 04:45:06

标签: c++ math cuda

您好我正在尝试在cuda中实现集成功能,但我不断在内核中获得访问冲突,我只是看不出原因!

#include <iomanip>    
#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#define R 10000
#define leftBound 1.0
#define rightBound 3.0
#define P 10

#define threads 512
#define MaxBlocks 65535

__global__ void cudaKernal(float *M, int x, int leftbound, float width)
{
    unsigned int index = blockIdx.x * threads + threadIdx.x;
    while(index < x)
    {
        int x = leftBound + width*index;
        M[index] = (float)((exp(-pow((float)x,2))*cos((float)(P*x))) * width);

        // Next run
        index += blockDim.x * gridDim.x;
    }
}

int main ()  
{    
    float width = (rightBound - leftBound) / R;
    int x = ceil((rightBound - leftBound) / width);
    float total = 0; 

    // Trick for celin the total blocks
    int TotalBlocks = (x+threads)/threads;
    if(TotalBlocks > MaxBlocks)
        TotalBlocks = MaxBlocks;

    float *dev_M;
    cudaMalloc((void**)&dev_M, x*sizeof(float));

    cudaKernal<<<TotalBlocks,threads>>>(dev_M, x, leftBound, width);

    float *M;
    cudaMemcpy( M, dev_M, x*sizeof(float), cudaMemcpyDeviceToHost);
    cudaFree(dev_M);

    for (int i = 0; i < x; ++i) { 
        printf("M[i]=%f", M[i]); 
        total += M[i]; 
    }    

    printf("The integral is: %f", total); 
    scanf_s("%f",123);
    return 0;
}

3 个答案:

答案 0 :(得分:3)

我在您的代码中看到的唯一访问冲突是:

while(index <= x)

不应该是:

while(index < x)

因为您为x准确分配了dev_M个元素,而且索引应该在[0..x-1]中。

答案 1 :(得分:2)

访问冲突可能在您的主机代码中:

float *M; 
cudaMemcpy( M, dev_M, x*sizeof(float), cudaMemcpyDeviceToHost); 
cudaFree(dev_M); 

你正在将记忆转移到M,但是我没有在任何可以看到的地方分配。

答案 2 :(得分:1)

这是因为您没有在主机上为M分配任何内存。这将解决问题:

float *M = (float*)malloc(x*sizeof(float));