C变量在线程迭代时不更新
我正在编写一个并行程序,它使用多个pthread来处理一个方阵中的值,直到它到达一个指定的点。我使用pthread屏障来通知线程启动,并让main知道何时更新矩阵 基本上,我有两个矩阵: readMatrix:包含writeMatrix要使用的当前迭代值。 writeMatrix:由线程使用readMatrix值运行的计算更新。 迭代完成后,读取和写入矩阵将交换。然后循环使用更新的读取矩阵继续 但是有一个问题,;迭代时,不会存储已交换的读取矩阵值 我正在使用结构将所有指针变量传递给启动的线程:C变量在线程迭代时不更新,c,struct,iterator,pthreads,memory-barriers,C,Struct,Iterator,Pthreads,Memory Barriers,我正在编写一个并行程序,它使用多个pthread来处理一个方阵中的值,直到它到达一个指定的点。我使用pthread屏障来通知线程启动,并让main知道何时更新矩阵 基本上,我有两个矩阵: readMatrix:包含writeMatrix要使用的当前迭代值。 writeMatrix:由线程使用readMatrix值运行的计算更新。 迭代完成后,读取和写入矩阵将交换。然后循环使用更新的读取矩阵继续 但是有一个问题,;迭代时,不会存储已交换的读取矩阵值 我正在使用结构将所有指针变量传递给启动的线程:
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);
}
总之,我需要readMatrix在迭代中实际存储更新后的值
任何帮助都将不胜感激
干杯因此交换发生在主线程中,您希望交换在所有其他线程中都可见?是的,迭代后在主线程中可见。为什么不将矩阵指针存储为2元素数组双**矩阵[2],分别初始化为readMatrix和writeMatrix。然后有一个全局标志来表示哪个是readMatrix,哪个是writeMatrix。只需切换标志以交换它们。你甚至不需要为每个线程存储它们,因为它们都使用同一个线程。好主意。因此,我现在这样做的原因是它在迭代后不会保留数据?您只是交换主线程的指针。工作线程仍然都有它们的旧指针,除非我遗漏了什么。实际上,您可能只需要将主线程的变量设置为全局变量,让其他线程只使用它们即可将readMatrix和writeMatrix从结构中取出。
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);
}