2016-10-11 50 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; 
}