【发布时间】:2020-11-09 04:05:00
【问题描述】:
我有以下问题:我的 C 程序必须计算文本文件中单词列表的出现次数。
我为此使用 OpenMP,并且该程序理论上具有正确的逻辑。当我将一些printfs 放入For Loop 中时,程序的结果是正确的并且总是相同的。
当我删除printfs 时,结果不正确,并且每次执行它的值都会改变。鉴于这种情况,我认为原因与执行时间有关。使用printfs 会增加执行时间,因此有时间完成对所有线程的计数,并且程序可以正常工作。如果没有prinfts,执行时间会呈指数级减少(0.000893 毫秒),没有时间完成所有线程/计算,因此程序会为每次执行打印不同的结果。
并行化代码如下:
#pragma omp parallel for schedule(dynamic) num_threads(threadNumber) private(word, wordExists) shared(keyWordsOcurrences)
for (line = 0; line < NUM_LINES; line++)
{
// divides the line into words separated by space
word = strtok(lines[line], " ");
while (word != NULL)
{
// checks if the word being read is one of the monitored words
wordExists = checkWordOcurrences(word);
if (wordExists)
{
#pragma omp critical
keyWordsOcurrences[wordExists - 1] += 1;
}
word = strtok(NULL, " ");
}
}
调用的 checkWordOcurrences 函数是我放置 printf 的地方,它负责使我的代码在每次执行中都能正常工作(增加执行时间)。
int checkWordOcurrences(char *word)
{
int res = 0;
int i;
for (i = 0; i < QTD_WORDS; i++)
{
// **this is the almighty Printf that makes everything work properly, and without it things stop working :(**
printf("palavra %d %s - palavra 2 %s \n", i, keyWords[i], word);
// compares current word with monitored words
if (!strcmp(keyWords[i], word))
{
// if it's monitored word, returns its index (+1 because the first word has index 0 and the return type is checked as true or false)
res = i + 1;
}
}
// returns word index or 0, if current word is not monitored
return res;
}
有人可以向我解释可能发生的情况和/或如何解决它吗?
【问题讨论】:
标签: c multithreading openmp