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;
}
I'm trying my hand at writing a naive indexOf function. It currently works and gets the right position. However it overflows when counting the number of comparisons. I've tried converting them all to long long ints but it doesnt seem to be making any difference. What can I do to fix this?
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
totalCom
变量是一个int
;这更有可能导致溢出。此外,您不需要#pragma omp critical
来更新totalCom
;将reduction(+ :totalCom)
添加到您的parallel for
标头中。The
totalCom
variable is anint
; that is more likely to be causing the overflow. Also, you don't need#pragma omp critical
to updatetotalCom
; addreduction(+ : totalCom)
into yourparallel for
header instead.