我正在编写一个并行程序,它使用多个pthread来操作方形矩阵中的值,直到达到指定点。我正在使用pthread屏障来指示线程启动并让main()知道何时更新矩阵。
基本上,我有两个矩阵:
迭代完成后,交换读写矩阵。然后循环使用更新的读取矩阵继续。
然而,有一个问题;在迭代中,不存储已交换的读取矩阵值。
我使用struct将所有指针变量传递给启动的线程:
struct matrixStruct {
double** readMatrix;
double** writeMatrix;
int dimension;
int totalThreads;
int threadNumber;
int lowerBound;
int upperBound;
};
这里是在main()中启动线程的位置,然后是控制线程的工作循环,交换矩阵并检查它是否已达到目标:
pthread_t threads[totalThreads];
int rc;
long t;
for( t = 0; t < totalThreads; t++)
{
structInstance[t].readMatrix = readMatrix;
structInstance[t].writeMatrix = writeMatrix;
structInstance[t].dimension = dimension;
structInstance[t].totalThreads = totalThreads;
structInstance[t].threadNumber = t;
structInstance[t].lowerBound = t*innerCellAmountByThread;
structInstance[t].upperBound = findUpperBound(t, innerCellAmountByThread, totalThreads, remainderOfCells);
rc = pthread_create(&threads[t], NULL, initiateThread, &structInstance[t]);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
int precisionCheck = 0;
// Working while loop
while(precisionCheck != 1) {
// Start all threads
pthread_barrier_wait(&barrier1);
// Wait for them to finish
pthread_barrier_wait(&barrier2);
// Swap matrix and then check for precision
double** tempMatrix;
tempMatrix = writeMatrix;
writeMatrix = readMatrix;
readMatrix = tempMatrix;
precisionCheck = verifyPrecision(readMatrix, writeMatrix, precision, dimension);
}
以下是每个主题的作用:
void *initiateThread(void *structArg) {
struct matrixStruct *structInstance = structArg;
double** readMatrix = structInstance->readMatrix;
double** writeMatrix = structInstance->writeMatrix;
int dimension = structInstance->dimension;
int totalThreads = structInstance->totalThreads;
int threadNumber = structInstance->threadNumber;
int lowerBound = structInstance->lowerBound;
int upperBound = structInstance->upperBound;
printf("threadNumber: %d lower: %d upper: %d\n\n", threadNumber, lowerBound, upperBound);
while(endFlag == 0) {
pthread_barrier_wait(&barrier1);
relaxMatrixWithBounds(readMatrix, writeMatrix, dimension, lowerBound, upperBound);
pthread_barrier_wait(&barrier2);
}
pthread_exit(NULL);
}
总而言之,我需要readMatrix来实际将更新的值存储在迭代中。
非常感谢任何帮助。
干杯