2013-07-08 39 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 
    } 
}