【发布时间】:2015-01-27 17:43:28
【问题描述】:
我正在尝试创建一个将依次迭代循环的 OpenMP 程序。我意识到线程不适用于顺序程序——与单线程相比,我试图获得一点加速,或者至少保持与单线程程序相似的执行时间。
在我的#pragma omp 并行部分中,每个线程计算自己的大数组部分并获取该部分的总和。这些都可以并行运行。然后我希望线程按顺序运行,并将每个总和添加到 TotalSum IN ORDER。所以线程 1 必须等待线程 0 完成,依此类推。我在#pragma omp 关键部分中有这部分。一切运行良好,除了只有线程 0 正在完成然后程序退出。如何确保其他线程继续轮询?我试过 sleep() 和 while 循环,但它在线程 0 完成后继续退出。
我没有使用#pragma omp parallel for,因为我需要跟踪每个线程访问的主数组的特定范围。以下是相关代码部分的缩短版本:
//DONE and MasterArray are global arrays. DONE keeps track of all the threads that have completed
int Function()
{
#pragma omp parallel
{
int ID = omp_get_thread_num
variables: start,end,i,j,temp(array) (all are initialized here)
j = 0;
for (i = start; i < end; i++)
{
if(i != start)
temp[j] = MasterArray[i];
else
temp[j] = temp[j-1] + MasterArray[i];
j++;
}
#pragma omp critical
{
while(DONE[ID] == 0 && ERROR == 0) {
int size = sizeof(temp) / sizeof(temp[0]);
if (ID == 0) {
Sum = temp[size];
DONE[ID] = 1;
if (some situation)
ERROR = 1; //there's an error and we need to exit the function and program
}
else if (DONE[ID-1] == 1) {
Sum = temp[size];
DONE[ID] = 1;
if (some situation)
ERROR = 1; //there's an error and we need to exit the function and program
}
}
}
}
if (ERROR == 1)
return(-1);
else
return(0);
}
这个函数在初始化线程数后从main调用。在我看来,并行部分完成了,然后我们检查错误。如果发现错误,则循环终止。我意识到这里出了点问题,但我无法弄清楚它是什么,现在我只是在兜圈子。任何帮助都会很棒。同样,我的问题是该函数仅在线程 0 执行后退出,但没有标记错误。我也让它在 pthreads 中运行,但执行起来更简单。 谢谢!
【问题讨论】:
标签: c multithreading parallel-processing openmp