2012-01-27 64 views
0

我尝试读取文件中的浮点数然后对它们进行排序。排序必须是并行UPC。这是目前的代码:UPC分配动态数组和排序

#include <upc_relaxed.h> 
#include <upc_collective.h> 
#include <stdio.h> 
#include <stdlib.h> 

int lt_int(shared void *x, shared void *y) { 
    int x_val = *(shared int *)x, 
    y_val = *(shared int *)y; 
    return x_val > y_val ? -1 : x_val < y_val ? 1 : 0; 
} 

shared int size=0; 

int main(int argc, char* argv[]) { 


    FILE *f; 
    int i=0; 
    if (MYTHREAD == 0) { 
    f = fopen ("dane.dat", "r"); 
    while (feof(f) == 0) {   
     fscanf (f, "%f\n");     
     ++size;  
    } 
    fclose(f); 
    } 

    upc_barrier; 

    /* allocation goes wrong! */ 
    shared [] float *array = upc_all_alloc(size, sizeof(float)); 
    /* printf("%d\n",sizeof(array)); // it returns 8! */ 

    upc_barrier; 

    if (MYTHREAD == 0) { 
    f = fopen ("dane.dat", "r"); 
    i=0; 
    while (feof(f) == 0) { 
     printf("%d\n", i); 
     /* segmentation fault! */ 
     fscanf (f, "%f\n", &array[i]);  
     printf("%f\n", array[i]);    
     i++;  
    } 
    fclose(f); 
    } 

    upc_barrier; 
    upc_all_sort(array, sizeof(float), size/THREADS, size, lt_int, UPC_IN_ALLSYNC); 
    upc_barrier; 

    if (MYTHREAD == 0) { 
    for (i = 0; i<=atoi(argv[1]) ; ++i) { 
     printf("%f\n", array[atoi(argv[1]) + (size/atoi(argv[1]))]); 
    } 
    } 

    return 0; 
} 

而我不知道我在做什么错。我得到分段错误,因为分配内存出错了。你可以帮我吗?

+0

你需要分配多于一个浮动值的空间,不是吗?为什么不尝试分配'sizeof(float)* THREADS'字节。 – Borealid 2012-01-27 00:07:26

+0

我试过了(我试过很多东西)。 sizeof(array)再次返回8,并且还有seqmentation错误:(。 – ciembor 2012-01-27 00:23:27

回答

1

此调用是错误的:

fscanf (f, "%f\n"); 

而且你的对象array是指向float。这是正常的sizeof array将返回指针类型的大小(在您的实现中为8),而不是您分配的数组对象的大小。您应该检查返回值upc_all_alloc以验证分配过程中没有错误(如果返回值== NULL,分配失败)。

+0

感谢您的建议,现在我正在寻找方法来计算我的文件中的浮点数......我发现我得到8 +(10 *行数)... – ciembor 2012-01-27 00:54:49