【问题标题】:Memory Race in CudaCuda 中的记忆竞赛
【发布时间】:2016-02-22 01:50:16
【问题描述】:

我有一个获取数组和数组索引的全局函数。 该函数需要在某个字典中找到一个单词,并在给定的序列中从哪里开始。

但我看到线程覆盖了结果。所以我猜这是因为记忆竞赛。 我该怎么办?

__global__ void find_words(int* dictionary, int dictionary_size, int* indeces, 
int indeces_size, int *sequence, int sequence_size, 
int longest_word, int* devWords, int  *counter)
{   
    int id = blockIdx.x * blockDim.x + threadIdx.x;
    int start = id * (CHUNK_SIZE - longest_word); 
    int finish = start + CHUNK_SIZE;
    int word_index = -1;

    if (finish > sequence_size)
    {
        finish = sequence_size;
    }
    // search in a closed area
    while(start < finish)
    {
    find_word_in_phoneme_dictionary_kernel(dictionary, dictionary_size, 
            indeces, indeces_size, sequence, &word_index, start, finish);

    if(word_index >= 0 && word_index <= indeces[indeces_size-1])
    {
        devWords[*counter]   = word_index; 
        devWords[*counter+1] = start;      // index in sequence 
        *counter+=2;
        start += dictionary[word_index];
    }
    else
    {
        start++;
    }
}
__syncthreads();
}

我还尝试为每个线程创建他自己的数组和计数器来存储他的结果 然后收集所有线程结果..但我不明白如何在 CUDA 中实现收集。有什么帮助吗?

【问题讨论】:

    标签: c++ cuda race-condition


    【解决方案1】:

    我猜问题是您的计数器被多个线程读取和递增。结果,多个线程将使用相同的计数器值作为数组中的索引。您应该改用int atomicAdd(int* address, int val); 来增加计数器。代码如下所示:

    int oldCounter = atomicAdd(counter, 2);
    devWords[oldCounter]   = word_index;
    devWords[oldCounter+1] = start;
    

    请注意,我在访问数组之前增加了 counteratomicAdd(...) 返回计数器的旧值,然后我用它来访问数组。 然而,原子操作是序列化的,这意味着递增计数器不能并行运行。不过,其余代码仍在并行运行。

    【讨论】:

    • 谢谢,但在我问这个问题之前我试过了,Visual Studio 2010 抱怨“atomicAdd 未定义”,我试图改变计算能力,但没有帮助..
    • 我的 Visual Studio 也是这么说的,但它仍然可以编译 ;) 编译器是否也说 atomicAdd 未定义?
    • 你还把计算能力设置为1.1或更高?
    • 我有 geforce gt 520M,计算能力为 2.1。但是Visual Studio,我将代码生成更改为compute_20,sm_21,您可以在此处看到stackoverflow.com/questions/14411435/…,但它仍然未定义
    • 目前看起来不错。在this question@G_fans 已接受答案的第一条评论中说,他在尝试更改计算能力和架构时遇到了同样的问题,因为该项目“从项目默认值继承了 compute_10、sm_10 值”。也许这也是你的问题?
    猜你喜欢
    • 2015-09-15
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 2013-02-17
    • 2014-06-06
    • 1970-01-01
    相关资源
    最近更新 更多