2017-04-23 69 views
0

我正在研究需要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]); 
      }} 
+0

隨着當前的代碼段,您向我們展示,它是很難推理你的代碼。請擴展您的問題以展示[最小,完整且可驗證的示例](https://stackoverflow.com/help/mcve)。 –

+0

我更新了我的答案,這是我的整個代碼。 –

+0

請勿使用石膏。就這麼簡單。 (不,實際上並不那麼簡單,有時候你必須這樣做,但作爲第一個接近這條規則的工作,你可以花幾年時間做C而不用寫一個單一的演員,當你最終需要一個演員時,你有足夠的經驗足以做到這一點) –

回答

1
pthread_create((pthread_t*)threadArr[i], NULL, findMaxPerArea, (void*)&inputArray[i]); 

鑄造threadArr[i]pthread_t*是沒有意義的,因爲你投一個值的指針。你不是要完全省去投(因爲你已經處理的pthread_t秒的陣列),並採取i個元素的地址:

&threadArr[i] 
+2

@GusAndrianos不客氣,但請不要在StackOverflow上使用任何髒話,它沒有得到很好的接收,並且可能會讓你的問題和答案被刪除。 –

+0

對不起,我正在尋找近一個小時。 –