我已经编辑了这个问题(希望)让问题更加清晰。 以下函数包含两个相同代码的块。每个块产生的输出是不同的。具体而言,在执行第一个临界区时,“done”变量未正确更新。关键部分确实具有保持输出不混合的效果。第二个代码块似乎产生预期的输出。产生的输出遵循代码。
有没有人对此行为有任何解释。我开始怀疑微软的一个错误。我正在使用Visual Studio 2010 Premium SP1进行开发。
感谢您提供的任何见解。
void OmpTest(int iterations)
{
int done;
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
done = 0;
#pragma omp parallel for
for (int ii = 0; ii < iterations; ++ii)
{
// do something useful
cv::Mat frame(32, 32, CV_8UC1, cv::Scalar(255));
// now update
#pragma omp critical
{
++done;
cout << setw(3) << 100 * done / iterations << "% "
<< setw(3) << done << " of " << setw(3) << iterations
<< " ii = " << ii << endl;
}
}
cout << endl;
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
done = 0;
#pragma omp parallel for
for (int ii = 0; ii < iterations; ++ii)
{
// do something useful
cv::Mat frame(32, 32, CV_8UC1, cv::Scalar(255));
// now update
#pragma omp critical
{
++done;
cout << setw(3) << 100 * done / iterations << "% "
<< setw(3) << done << " of " << setw(3) << iterations
<< " ii = " << ii << endl;
}
}
cout << endl;
}
输出:
% OmpTest
6% 1 of 16 ii = 0
12% 2 of 16 ii = 1
6% 1 of 16 ii = 8
6% 1 of 16 ii = 6
6% 1 of 16 ii = 12
6% 1 of 16 ii = 2
6% 1 of 16 ii = 4
6% 1 of 16 ii = 14
12% 2 of 16 ii = 15
12% 2 of 16 ii = 9
12% 2 of 16 ii = 7
12% 2 of 16 ii = 13
12% 2 of 16 ii = 3
12% 2 of 16 ii = 5
6% 1 of 16 ii = 10
12% 2 of 16 ii = 11
6% 1 of 16 ii = 10
12% 2 of 16 ii = 2
18% 3 of 16 ii = 3
25% 4 of 16 ii = 14
31% 5 of 16 ii = 15
37% 6 of 16 ii = 12
43% 7 of 16 ii = 8
50% 8 of 16 ii = 4
56% 9 of 16 ii = 11
62% 10 of 16 ii = 6
68% 11 of 16 ii = 0
75% 12 of 16 ii = 13
81% 13 of 16 ii = 9
87% 14 of 16 ii = 5
93% 15 of 16 ii = 7
100% 16 of 16 ii = 1