1
當我嘗試在openmp for循環中移動一個malloc調用時,我遇到了Seg故障的一個有趣問題。每個線程都必須計算它自己的距離向量副本,以正確計算分類,因此向量必須是私有的......但是,當我嘗試使用多於1個線程調用它時,它會導致seg錯誤。如果將p_distances向量聲明爲共享,則不會發生這種情況,儘管這會導致線程相互覆蓋,從而導致距離計算不準確。是否存在一些非常明顯的規則,我在這裏違反了...另外,我知道在我的代碼中還有其他不好的代碼實踐。我總是樂於提出有關風格的建議,但請幫助我關注實際導致問題的原因。Private Malloc的OpenMP Seg Fault
int *labels_train;
float *data_train;
int *labels_test;
float *data_test;
float *s_distances;
int *s_results, *p_results;
int i, j, k, h;
int N, D, K, M, thread_count;
void sort(float *_distances, int *_labels_train, int _N);
void computeParallelKNN()
{
// this is the target loop for multi-point parallelization
// seg fault here whenever p_distances malloc is moved inside parallel for loop and declared private
#pragma omp parallel for num_threads(thread_count) private(h, j, i)
for (i = 0; i < M; i++)
{
float *p_distances = (float*)malloc(N * sizeof(float));
k = 0;
// This is the target loop for single point parallelization
// No dependencies on outer loop (each thread can calculate distance for current point with some
// different training point)
for (h = 0; h < N*D; h+=D)
{
float dTmp = 0;
// Reduction operation..no dependencies here either (I don't think?)
// dTmp is critical variable for parallel operations
for (j = 0; j < D; j++)
{
dTmp += pow(data_test[i*D+j] - data_train[h+j],2);
}
p_distances[k] = (float)sqrt((double)dTmp);
k++;
}
// Make a copy of labels (since sort will invalidate original data/labels correlation)
int *temp_labels;
temp_labels = (int*)malloc(N * sizeof(int));
for (h = 0; h < N; h++)
temp_labels[h] = labels_train[h];
// Sort distances/labels_train vector
sort(p_distances, temp_labels, N);
// Calculate/print KNN classification
int neg = 0;
int pos = 0;
for (h = 0; h < K; h++)
{
if(temp_labels[h] == -1) neg++;
else pos++;
}
if (pos > neg) p_results[i] = 1;
else p_results[i] = -1;
free(p_distances);
}
}
// Selection sort algorithm modified to sort labels according to distance data
void sort(float *_distances, int *_labels_train, int _N)
{
int k;
for (k = 1; k < _N; ++k)
{
float dist_key = _distances[k];
int label_key = _labels_train[k];
int i = k - 1;
while ((i >= 0) && (dist_key < _distances[i]))
{
_distances[i + 1] = _distances[i];
_labels_train[i + 1] = _labels_train[i];
--i;
}
_distances[i + 1] = dist_key;
_labels_train[i + 1] = label_key;
}
}
我可以張貼的完整代碼,但是這絕對是在故障發生的區域。在此先感謝,希望這只是我犯的一個愚蠢的錯誤。
我不是100%肯定,爲什麼你的代碼不能正常工作。但是你是否嘗試過在循環外聲明p_distance,並按照以下方式爲每個線程分配它:'#pragma omp parallel private(p_distance,i,j,k etc。)\ n {p_distance = calloc(N,sizeof(float )); \ n #pragma omp for \ n {for(i = 0; i
Bort