如何从不同线程CUDA写入全局内存

How to write in global memory from different threads CUDA

我有一个在不同数组中搜索的内核(每个数组一个线程),我需要一个线程始终找到匹配项,结果将写入全局内存数组。问题是如何在不在同一位置写入两次或将位置留空的情况下访问这个全局数组?

这是我正在尝试做的伪代码示例:

__global__ void find(*TableOfArrays, *Result, position)
{
   int idx = blockIdx.x * blockDim.x + threadIdx.x;
   if (idx < numOfArrays)
   {
     for (int i = 0; i < tableOfArrays[idx].lenght; i++)
     {
        if (Match(tableOfArrays[idx][i]))
        {
            //The position variable gives me the position of the global array.  
            atomicAdd(&(position), (int)1);
            //I want to write each result in one space of the array Result
            Result[position] = tableOfArrays[idx][i];
        }   
     }
   }
}

问题是线程没有按顺序访问结果数组,有些线程采用相同的方法space...有帮助吗?谢谢你。

atomicAdd读取内存时必须取变量的值,atomicAdd执行后另一个线程可以访问内存并修改它。

int localIndex = atomicAdd(&(position), (int)1);
Result[localIndex] = tableOfArrays[idx][i];