2016-10-11 77 views
1

我正在開發一個需要與下面的程序有點類似功能的項目,所以我試圖創建一個更簡單的程序來調試我的大型程序。我創建的線程返回的值與預期輸出不一致,但返回值不是隨機的。它幾乎看起來像線程正在返回其他線程的值,或者它們返回的變量(「tmp」)正在更新。線程返回值與預期輸出不一致

預期的輸出應該是...

#include <stdio.h> 
#include <pthread.h> 

struct Numbers { 
    int x; 
    int y; 
}; 

void *go(void* param) 
{ 
    struct Numbers* nums = (struct Numbers*) param; 
    int sum = nums -> x + nums -> y; 

    return (void*) sum; 
} 

int main() 
{ 
    int result[2][2]; 
    int tmp; 

    pthread_t thread[2][2]; 

    int i, j; 
    for(i=0;i<2;i++) 
    { 
     for(j=0;j<2;j++) 
     { 
      struct Numbers nums; 
      nums.x = i; 
      nums.y = j; 

      pthread_create(&thread[i][j], NULL, go, &nums); 
     } 
    } 

    for(i=0;i<2;i++) 
    { 
     for(j=0;j<2;j++) 
     { 
      pthread_join(thread[i][j], (void*) &tmp); 
      result[i][j] = tmp; 
     } 
    } 

    for(i=0;i<2;i++) 
    { 
     for(j=0;j<2;j++) 
     { 
      printf("%d\t", result[i][j]); 
     } 
     printf("\n"); 
    } 

    return 0; 
} 
+4

考慮nums'的'壽命相比,當線程可能會嘗試訪問它。 – GManNickG

+1

你是否保證'nums',不會被重寫所有的線程調用? – dvhh

+0

@GManNickG我有一個完美的「Ohhhhh」時刻。所以我唯一的選擇是在創建線程之前準備所有的數據(嵌套的for循環之外)還是有更好的選擇? –

回答

2

你傳遞一個變量,一旦線程開始可能將不存在的地址正在執行,或者至少會被多個線程看到,或者是一個線程在其他線程讀取數據時寫入數據競爭。

一個通用的解決方案是動態分配線程的參數和結果,並讓調用者和線程以這種方式進行通信。

例子:

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 

struct threadargs { 
    int x; 
    int y; 
}; 

struct threadresults { 
    int sum; 
    int product; 
}; 

void* threadfunc(void* args_void) { 
    // Get thread args in usable type. 
    struct threadargs* args = args_void; 
    struct threadresults* results = NULL; 

    //Compute. 
    int sum = args->x + args->y; 
    int product = args->x * args->y; 

    // Return the result.  
    results = malloc(sizeof(*results)); 
    results->sum = sum; 
    results->product = product; 

    free(args); 
    return results; 
} 

int main() 
{ 
    pthread_t thread[2][2]; 
    struct threadresults* results[2][2] = {0}; 

    int i, j; 
    for (i = 0;i < 2; ++i) { 
     for (j = 0; j < 2; ++j) { 
      struct threadargs* args = malloc(sizeof(*args)); 
      args->x = i; 
      args->y = j; 

      pthread_create(&thread[i][j], NULL, threadfunc, args); 
     } 
    } 

    for (i = 0; i < 2; i++) { 
     for (j = 0; j < 2; j++) { 
      void* result; 
      pthread_join(thread[i][j], &result); 
      results[i][j] = result; 
     } 
    } 

    for (i = 0; i < 2; i++) { 
     for (j = 0; j < 2; j++) { 
      printf("sum: %d\tproduct: %d\n", 
        results[i][j]->sum, results[i][j]->product); 
     } 
    } 

    for (i = 0; i < 2; i++) { 
     for (j = 0; j < 2; j++) { 
      free(results[i][j]); 
     } 
    } 

    return 0; 
}