我正在研究需要pthread使用的東西。基本上,我想在一個矩陣上找到最大值,但是不用做所有單處理的工作,我使用pthreads
來分解它。 我使用一個結構,如下定義,輸入findMaxPerArea
函數的多個值。發生問題時,我在最後一行撥打pthread_create(...);
。它通過之前的printf
罰款。 請不要對我太難,因爲我知道這一定是一個愚蠢的錯誤。有什麼想法嗎?調用pthread_create時發生分割錯誤,傳遞一個struct
struct inputData{
int ** array;
int start, stop, cols, threadID;
int* localmax;
};
void* findMaxPerArea(void* tmp){
struct inputData* inp = (struct inputData*) tmp;
inp->localmax[inp->threadID] = 0;
int i, j;
for(i = inp->start; i < inp->stop; i++){
for(j = 0; j < inp->cols; j++){
if(inp->array[i][j] > inp->localmax[inp->threadID]) inp->localmax[inp->threadID] = inp->array[i][j];
}
}
}
int main(){
int N, p;
printf("Give me the number of threads\n");
scanf("%d", &p);
printf("Give me the number of rows and columns (one value)\n");
scanf("%d", &N);
int* localmax = malloc(p * sizeof(int));
pthread_t* threadArr = (pthread_t*) malloc(p*sizeof(pthread_t));
int** a = malloc(N * sizeof(int*));
for (int i = 0; i < N; i++) {
a[i] = malloc(N * sizeof(int));
}
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
a[i][j] = 5;
}
}
a[0][1] = 8;
a[1][1] = 13;
struct inputData* inputArray = (struct inputData*) malloc(p * sizeof(struct inputData));
for(int i = 0; i < p; i++){
inputArray[i].array = a;
inputArray[i].start = i*(N/p);
inputArray[i].stop = (N/p)*(i+1) - 1;
inputArray[i].cols = N;
inputArray[i].threadID = i;
inputArray[i].localmax = localmax;
printf("It passes this\n");
pthread_create((pthread_t*)threadArr[i], NULL, findMaxPerArea, (void*)&inputArray[i]);
}}
隨着當前的代碼段,您向我們展示,它是很難推理你的代碼。請擴展您的問題以展示[最小,完整且可驗證的示例](https://stackoverflow.com/help/mcve)。 –
我更新了我的答案,這是我的整個代碼。 –
請勿使用石膏。就這麼簡單。 (不,實際上並不那麼簡單,有時候你必須這樣做,但作爲第一個接近這條規則的工作,你可以花幾年時間做C而不用寫一個單一的演員,當你最終需要一個演員時,你有足夠的經驗足以做到這一點) –