在OpenMP中溢出int

时间:2011-03-11 01:02:46

标签: c overflow openmp

我正在尝试编写一个天真的indexOf函数。它目前正在运作并获得正确的位置。但是,在计算比较次数时会溢出。我已经尝试将它们全部转换为长时间的整数但它似乎没有任何区别。我该怎么做才能解决这个问题?

int hostMatch(long long int *comparisons)
{
    long int i,j,k, lastI;

    i=0;
    j=0;
    k=0;
    lastI = textLength-patternLength;
    *comparisons=0;

    int lastIi = lastI+1;
    int position = -1;

    int numberThreads = 1;
    int totalCom = 0;

    #pragma omp parallel for default(none) num_threads(numberThreads) \
        shared(totalCom, position) \
        private(i,j,k) \
        firstprivate(lastIi,patternLength, textData, patternData)
    for (i=0;i<lastIi;i++)
    {
        if (position != -1)
        {
            // found
        }
        else
        {
            k=i;
            long long int count = 0L;
            for (j=0;j<patternLength;j++)
            {
                count++;
                if (textData[k] == patternData[j])
                {
                    if (j == patternLength - 1)
                    {
                        // found
                        position = i;
                    }
                }
                else
                {
                    break;
                }
                k++;
            }
            #pragma omp critical (totalLock)
            {
                totalCom += count;
            }
        }
    }
    /* END OF PARALLEL SECTION*/
    printf("Total Comparisons = %i\n", totalCom);
    (*comparisons) = totalCom;
    return position;
}

1 个答案:

答案 0 :(得分:1)

totalCom变量是int;这更有可能导致溢出。此外,您不需要#pragma omp critical来更新totalCom;将reduction(+ : totalCom)添加到您的parallel for标题中。