2013-07-08 37 views
0

我想在C中設計一個小程序。我使用openMP來並行化部分代碼,它通過逐行讀取文件,存儲大量的行讀取數組緩衝區並調用一個函數,該函數現在'等待'10微秒。這是我的代碼。 我基本上想要並行執行該特定功能。 即緩衝區的數據一旦被填滿就被分配到單個線程上,然後第二個緩衝區填滿第二個線程,等等......。這可能不同步,並且不需要在此階段。使用openmp並行函數調用

int count = 0;    //global 
char *array_buffer[8];  //global 

char process(int lent) 
{ 
    int row,col; 
    #pragma omp single 
     for(row = 0; row<count; row++) 
    { 
     usleep(10); 
       //printf("%s", array_buffer[row]); 

       //may be executing another function call from here .... ? 

       free(array_buffer[row]); 
    } 
    return 1; 
} 


void line(char *line_char) 
{ 

    int lent = strlen(line_char); 

    array_buffer[count] = malloc((lent + 1)*sizeof(char)); 
    strcpy(array_buffer[count], line_char); 

    #pragma omp parallel 
    if (count == 8) 
    { 
    int returning, returned_all = 0; 
    returning = process(lent); //function call, waits for 10 microseconds and returns 1 as o/p 

    #pragma omp single 
    count = 0; 

    #pragma omp atomic 
    returned_all = returned_all + returning; 
    } 

    count++; 
} 



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

    FILE *fp = fopen(argv[1], "r"); 
    if(fp == NULL) 
    { 
     printf("Couldn't open file %s",argv[1]); 
    } 
    char buff[512]; 

    while (fgets(buff, 512, fp) != NULL) 
    { 
     line(buff);    /*sending out an array having one line*/ 
    } 

    return 0; 
} 

這顯然不起作用。我知道我搞砸了omp單,但omp原子似乎是正確的。任何幫助,建議或更正,讓這個工作?

回答

2

我甚至不知道從哪裏開始。

你的代碼有太多錯誤。

第一:你知道你的並行代碼只能運行在第8行嗎?

if (count == 8) 

您平行塊內分配returned_all,這意味着每個線程都有它自己的私人returned_all副本。

您使用#pragma omp single是完全不合適的。如果使用#omp parallel塊以外的塊,它將不會影響編譯...

在並行函數中調用free(array_buffer[row])會使您在使用double free等時遇到很多麻煩。

如果你想通過平行線來處理一個文件行,我建議你使用的stdio庫的默認鎖定,並完成類似

#pragma omp parallel 
{ 
    // each thread get's it's own private buffer 
    char buff[512]; 
    while (fgets(buff, 512, fp)) { 
     // process the line 
    } 
}